Sunday, May 28, 2023

Angular- Directive to Allow Number Only in Input Textbox

Directive to Allow Number Only in Input Textbox

In this post, we will create a directive which will allow only numbers to input textbox. User will not allow to enter any other value, only numbers.

Below is the code of directive which will check the input value and allow if the input value is number-

import { Directive, HostListener } from '@angular/core';

@Directive({ selector: '[allowNumberOnly]' })
export class AllowNumberOnly {
  readonly NUMBER_REGEX = '^[0-9]';
  @HostListener('keypress', ['$event'])
  onKeyPress(event: any): boolean {
    if (!new RegExp(this.NUMBER_REGEX).test(event.key)) {
      return false;
    }
    return true;
  }
}

To use the directive in application, we need to add the directive under declarations array of App Module file.

@NgModule({
  declarations: [
    AppComponent,
    MyComponentComponent,
    AllowNumberOnly, //<--- Add your directive here
  ],
  imports: [BrowserModule, AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

After adding the directive in App Module, we can use the directive in out html shown as below-

App Component

Demo-

You can find some more usefull Angular topics here.

No comments:

Post a Comment

^ Scroll to Top