that's because when you were doing ans = Serial.readString();you had in your ans variable also the extra invisible end of line characters (carriage return, line feed - whatever you had selected in the Serial monitor). So when you were performing the comparison if (ans=="on") that was failing as there was no match for these invisible characters.
by removing the end of line, the call Serial.readString() will get what's coming and then timeout (after 1s) and you only get "on" or whatever you typed in the ans variable. Then it works.