Is there a simple number input with Angular reactive forms and matInput?

43 views Asked by At

There is no native number validator (https://angular.io/api/forms/Validators), but you can easily do a pattern Validators.pattern('^[0-9]*$').

But even with the validator, the user can still type any character, then get an error or not. How can I have a simple input that will only accept numbers?

Edit: my input="number" was overwritten by other code that I missed, so my bad, matInput does work as a native input when you set it to number.

3

There are 3 answers

0
Jaykant On

Use a directive to enforce input field, which will ensure that only numbers are accepted in the input field.

Create a OnlyNumberDirective like below and use it in template

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[appOnlyNumber]'
})
export class OnlyNumberDirective {
    constructor(private el: ElementRef) { }
      @HostListener('input', ['$event']) onInputChange(event) {
        const initialValue = this.el.nativeElement.value;
        this.el.nativeElement.value = initialValue.replace(/[^0-9]*/g, '');
        if (initialValue !== this.el.nativeElement.value) {
          event.stopPropagation();
        }
      }
}

This directive accept only numeric values in the input field by filtering out any non-numeric characters as the user types.

0
Varun Savaliya On

There is one simple solution for your issue, you can make one method which will do the thing for you like below...

numberKeyValidation(event) {
    const charCode = event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      event.preventDefault();
      return;
    }
}

Then use it on your input fields like this...

<input placeholder="Your age..."
       (keypress)="numberKeyValidation($event)"/>

This will prevent everything other than numbers.

TIP: Make this method in your shared service and use it everywhere.

Happy Coding!!!

0
Rashmi Yadav On

To handle validation for input type number, we can create a custom validator that checks for number only. Here's the code snippet:

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[InputFormatter]'
})
export class InputFormatterDirective {
    constructor() { }
      @HostListener('keydown', ['$event']) formatInputText(event) {
      let e = <KeyboardEvent>event;
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                    e.preventDefault();
                }
      }
}

Use it in the HTML(template) of your code like this:

<input type="text" InputFormatter>

Hope it helps!!!Happy coding