简体   繁体   中英

How do I prevent user Input continuous "00" in Angular8?

I use Angular8 and I want prevent user Input continuous "0" in a Input element.

if user Input "00" I want it display as "0", if user input "01", I want delete the first "0" in the string => it should becomes "1".

I change the value in ngModelChange() , my problem is : the ngModel changed indeed . but the input element still display the old value.

and I have a template for it : Check this link

and it just won't work, can anyone tell me the solution?

If you're only expecting whole numbers (or you don't mind rounding down), you could use Math.floor() . Note that this won't work in strict mode.

 let test = Math.floor(00); let test2 = Math.floor(01); console.log(test, test2);

Update

So this has been fun. Javascript is treating 0123 as a binary literal . Turns out forcing base10 with parseInt is the way to go. Note, you have to be sure you are parsing a string for this to work.

 let test = Math.floor(00); // 0 let test2 = Math.floor(01); // 1 let test3 = Math.floor(0123); // 83 let test4 = parseInt(0123); // 83 let test5 = parseInt(0123, 10); // 83 let test6 = parseInt('0123', 10); // 123 console.log(test, test2, test3, test4, test5, test6);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM