Is it possible to implement an input
that allows to type only numbers inside without manual handling of event.target.value
?
In React, it is possible to define value
property and afterwards input change will be basically bound to the value (not possible to modify it without value
change). See example. And it works just fine without any efforts.
In Angular 2 it is possible to define [value]
, but it will just set the value initially, and afterwards input
is not prevented from the modifications.
I was playing around with ngModel
and [value] / (input)
, see example.
But in both implementation there is essential problem:
How to do that simple (from the first glance) component, without manually handling event.target.value
?...
UPDATE I am not looking for native HTML5 input[number]
element here. Numbers input here is just for the example - there could be way more tasks when i need to restrict input text.
Moreover, input[number]
is 1) not restricting me from typing 10ddd
and 2) (less important) contains arrows that i do not need.
And the problem here is to prevent user from typing something beyond the restricted values, instead of allow to input anything and validate it afterwards
To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.
To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.
In component.ts add this function
_keyUp(event: any) { const pattern = /[0-9\+\-\ ]/; let inputChar = String.fromCharCode(event.key); if (!pattern.test(inputChar)) { // invalid character, prevent input event.preventDefault(); } }
In your template use the following
<input(keyup)="_keyUp($event)">
This will catch the input before angular2 catches the event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With