How to restrict numbers and special characters input in textbox Angular 7?
Stayed Informed - Allow Only Numbers Input in Textbox in Angular 7
I am sharing an example for allow only numeric in
Textbox Angular 7, following steps involved:-
1. Create
Angular directive to allow only numeric input
2. Import
this directive in NgModule
3. Use
above created directive in your components to apply this
Let’s
see the example –
Create Directive to allow only numeric input –
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[OnlyNumeric]'
})
export class OnlyNumericDirective {
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 { OnlyNumericDirective } from './directive/only-numeric.directive';
@NgModule({
declarations: [
OnlyNumericDirective
],
imports: [
],
providers: [
],
bootstrap: [AppComponent]
})
export class AppModule { }
Components
– The Interest rate field should be only numeric input by using the directive –
OnlyNumeric.
<input type="text" OnlyNumeric required [(ngModel)]="model.InterestRate" id="InterestRate" name="InterestRate" class="form-control" placeholder="Interest
rate">
Result looks like –