In this post, we will create a directive which will allow only numbers to input textbox. User will not allow to enter any other value, only numbers.
Below is the code of directive which will check the input value and allow if the input value is number-
import { Directive, HostListener } from '@angular/core'; @Directive({ selector: '[allowNumberOnly]' }) export class AllowNumberOnly { readonly NUMBER_REGEX = '^[0-9]'; @HostListener('keypress', ['$event']) onKeyPress(event: any): boolean { if (!new RegExp(this.NUMBER_REGEX).test(event.key)) { return false; } return true; } }
To use the directive in application, we need to add the directive under declarations array of App Module file.