DEV Community

Cover image for Restrict Angular input to number only
dilika 🤩
dilika 🤩

Posted on • Updated on

Restrict Angular input to number only

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();
        }
    }

}
Enter fullscreen mode Exit fullscreen mode
  • In your app.module.ts, add: NumberRestricDirective to your declarations like that:
@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent , NumberRestricDirective ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Enter fullscreen mode Exit fullscreen mode

-Add restrictNumbers attribute to your input balise :

<input  type="text" [(value)]="value" restrictNumbers/> 

Enter fullscreen mode Exit fullscreen mode

And It's Okay

Top comments (0)