Angular2 deletes invalid inputs for <input type=“number”>?

青春壹個敷衍的年華 提交于 2019-12-24 10:12:42

问题


See this plunkr: https://plnkr.co/edit/nGKAnXrrzgKSxpkdvEhX?p=preview

I have a simple <form> in Angular that displays a <input type="number"> field.

When I enter something like "123" everything is ok.

But the input "123-456" seems to be ok, too, although this is not a "real" number. I found out that Angular sets the myNumber.value to null and so everything seems to be ok.

What I want to achieve is that Angular doesn't reset the input "123-456" to null and instead tells me that the input is invalid.

How can I achieve that?


回答1:


You can remove the type="number" add a simple function that allows only numbers and - key.

<input formControlName="myNumber" #myNumber (keydown)=onlyNumberKey($event)><br>

onlyNumberKey(event){
        let charCode = (event.query) ? event.query : event.keyCode;
        console.log(charCode);
            if (charCode != 189 && charCode > 31
                && (charCode < 48 || charCode > 57))
                return false;
            return true;
    }

Plunker



来源:https://stackoverflow.com/questions/45015048/angular2-deletes-invalid-inputs-for-input-type-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!