You must create a directive, directives in Angular allow you to attach behavior to elements in the DOM.
- Create a file: number-restrict.directive.ts
import {Directive, ElementRef, EventEmitter, HostListener, Output} from '@angular/core';
@Directive({
selector: 'input[restrictNumbers]'
})
export class NumberRestricDirective {
@Output() valueChange = new EventEmitter()
constructor(private elementRef: ElementRef) {
}
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this.elementRef.nativeElement.value;
const newValue = initalValue.replace(/[^0-9]*/g, '');
this.elementRef.nativeElement.value = newValue;
this.valueChange.emit(newValue);
if (initalValue !== this.elementRef.nativeElement.value) {
event.stopPropagation();
}
}
}
- In your app.module.ts, add: NumberRestricDirective to your declarations like that:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent , NumberRestricDirective ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
-Add restrictNumbers attribute to your input balise :
<input type="text" [(value)]="value" restrictNumbers/>
And It's Okay
Top comments (0)