DEV Community

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

Posted on • Edited on

5

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)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post