问题
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