allow only numbers

Angular 7 Directive - Allow Only Numbers Input in TextBox Example

How to restrict alphabets and special characters input in textbox Angular 7?
I am sharing an example for allow only numbers in Textbox Angular 7, following steps involved:-
1.      Create Angular directive to allow only numbers input
2.      Import this directive in NgModule
3.      Use above created directive in your components to apply this

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';
import { OnlyNumericDirective } from './directive/only-numeric.directive';

@NgModule({
  declarations: [
    AppComponent,
    OnlynumberDirective,
    OnlyNumericDirective
  ],
  imports: [
  ],
  providers: [
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Components – The Loan Amount field should be only number input by using the directive - numbersOnly

<input type="text" numbersOnly required  [(ngModel)]="model.LoanAmount" id="LoanAmount" name="LoanAmount" class="form-control" placeholder="Loan amount">

Result looks like –
Stayed Informed - Allow Only Numeric Input in Textbox in Angular 7
ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.
^