In Angular2, how can I mask an input field(textbox) such that it accepts only numbers and not alphabets?
I have the following HTML input:
<input type="text" *ngSwitchDefault class="form-control" (change)="onInputChange()" [(ngModel)]="config.Value" focus)="handleFocus($event)" (blur)="handleBlur($event)"/>
The above input is a generic text input which may either be used as a simple text field or as a numeric field, (for example to show the Year).
Using angular2, how can I use the same input control and apply some sort of filter/mask on this field, such that it accepts only numbers? What are the different ways I can achieve this?
Note: I need to achieve this using only textbox and not using input number type.
Just Create a directive and add below hostlistener:
Replace invalid text with empty. All keys and key combinations will now work across all browsers till IE9.
I have made some modifications in the above directive and implemented min, max, maxlength.
You can use angular2 directives. Plunkr
and you need to write the directive name in your input as an attribute
don't forget to write your directive in declarations array of your module.
By using regex you would still need functional keys
In order to accomplish this, I bound a function to the onInput method like this:
(input)="stripText(infoForm.get('uin'))
Here is the example inside my form:
Then I added the following function to my component:
This regex
/[^0-9]/g
searches for anything that is not a number and using.replace
I set it to be replaced by nothing. So when a user tries to type in a character that is not a number (in this case a character that is not zero through nine), it appears as if nothing happens in the text box.Here is easy one: Simple directive On keydown event it checks the length of a key is one and key is not a number to
preventDefault()
and it won't renders that char.HTML:
Limitations: It will allow pasting using a mouse that way will accept other char. To avoid that you can pass the model as input to the directive and
ngOnChage
to that model change value to only numbers:Like below:
EDIT: Added Code to detect change in Model and update the input's value
HTML:
Use directive to restrict the user to enter only numbers in the following way:
In HTML:
Angular2:
And need to write the directive name in your input as an attribute.