简体   繁体   English

如何防止用户在 Angular8 中连续输入“00”?

[英]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.我使用 Angular8,我想防止用户在 Input 元素中输入连续的“0”。

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".如果用户输入“00”我希望它显示为“0”,如果用户输入“01”,我想删除字符串中的第一个“0”=>它应该变成“1”。

I change the value in ngModelChange() , my problem is : the ngModel changed indeed .我改变了 ngModelChange() 中的值,我的问题是:ngModel 确实改变了。 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() .如果您只期望整数(或者您不介意四舍五入),则可以使用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 . Javascript 将 0123 视为二进制文字 Turns out forcing base10 with parseInt is the way to go.事实证明,使用parseInt强制 base10 是可行的方法。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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