How to restrict alphabets and special characters input in textbox Angular 9?
I am sharing an example for allowing only numbers in Textbox
- Create Angular directive to allow only numbers input
- Import this directive in module
- Use the above-created directive in your components
Let’s see the example
Create Directive to allow only numbers input
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[numbersOnly]'
})
export class OnlyNumberDirective {
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();
}
}
}
Import directive in NgModule
import { OnlyNumberDirective } from '../app/directive/onlynumber.directive';
@NgModule({
declarations: [
AppComponent,
OnlyNumberDirective,
],
imports: [
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule { }
Components – The Amount field should be only number input by using the directive – numbersOnly
<input type="text" numbersOnly required [(ngModel)]="model.Amount"
id="Amount" name="Amount" class="form-control" placeholder="Amount">