Angular

Allow Only Numbers – Angular 9 Directive

How to restrict alphabets and special characters input in textbox Angular 9?I am sharing an example for allowing only numbers in Textbox...

Written by Luci · 37 sec read >

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">
Written by Luci
I am a multidisciplinary designer and developer with a main focus on Digital Design and Branding, located in Cluj Napoca, Romania. Profile

Angular Basics: The CLI and Components

Luci in Angular
  ·   7 min read
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x