In this post, we will see how to allow an Input field only with numbers using Directive. This example is tested in the Angular 8 version.
We won't allow any alphabets, decimals, or special characters and allow backspace, delete, copy, and paste. Here we are using an attribute directive to allow numbers only in the input textbox field to do the client side validation.
Directive
Generate type using the following command,
ng generate directive allownumbersonly
AppModule will be automatically imported with Numbers only Directive.
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appAllownumbersonly]'
})
export class AllownumbersonlyDirective {
constructor(private el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this.el.nativeElement.value;
this.el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if (initalValue !== this.el.nativeElement.value) {
event.stopPropagation();
}
}
}
Annotate the TypeScript class with @Directive and use the selector as an attribute in input element like below,
Default App Component HTML
<input appAllownumbersonly type="text">
The selector is used in default parent components HTML file generated during creating a project through command.
To see the other use case of allownumbersonly see the Angular Phone number validation example.