Allow only numbers in a text input with Angular

10,358

Solution 1

Try this directive. Listen for the input event to also handle copy and paste.

export class NumberOnlyDirective {
  constructor(private el: NgControl) {}

  @HostListener('input', ['$event.target.value'])
  onInput(value: string) {
    // NOTE: use NgControl patchValue to prevent the issue on validation
    this.el.control.patchValue(value.replace(/[^0-9]/g, ''));
  }
}

Solution 2

You can use Ng Knife utility

  1. Import NgKnifeModule

    ... 
    import { NgKnifeModule } from 'ng-knife';
    ...
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        NgKnifeModule
      ],
      ...
    });
    export class AppModule { }
    
  2. Using it:

    <!-- Only Numbers -->
    <input knifeOnlyNumbers type="text">
    
Share:
10,358
VR1256
Author by

VR1256

Updated on June 18, 2022

Comments

  • VR1256
    VR1256 almost 2 years

    I am trying to write code which will allow only numbers in a text input text. I've written the following directive.

    import { Directive, ElementRef, Input, HostListener } from '@angular/core'
    
    @Directive({
        selector: '[appAllowNumberonly]'
    })
    export class AllowNumberonlyDirective {
    
        private el: HTMLInputElement;
    
        constructor(private elementRef: ElementRef) {
            this.el = this.elementRef.nativeElement;
        }
    
        @HostListener("keydown", ["$event"])
        onKeyDown(e: KeyboardEvent) {
            if (this.el.value == undefined) {
                this.el.value = '';
            }
            let transformedInput = this.el.value.replace(/[^0-9]/g, '');
            if (transformedInput != this.el.value) {
                this.el.value = transformedInput;
            }
        }
    
        @HostListener("keyup", ["$event"])
        onKeyUp(e: KeyboardEvent) {
            if (this.el.value == undefined) {
                this.el.value = '';
                e.preventDefault();
            }
            let transformedInput = this.el.value.replace(/[^0-9]/g, '');
            if (transformedInput != this.el.value) {
                this.el.value = transformedInput;
            }
            return transformedInput;
        }
    
        @HostListener("blur", ["$event.target.value"])
        onBlur(value) {
            if (this.el.value == undefined) {
                this.el.value = '';
            }
            let transformedInput = this.el.value.replace(/[^0-9]/g, '');
            if (transformedInput != this.el.value) {
                this.el.value = transformedInput;
            }
        }
     }
    

    This works perfectly fine, but user is able to enter value into the text box and then my directive is removing the values that are non-numeric, but I want to stop user from entering into the textbox, how can I achieve that?

    I want to cover copy paste scenario with mouse as well.

    I have below Plunker which works perfectly fine in AngularJS (1.x), how do I convert to Angular? I am unable to use parsers.

    http://jsfiddle.net/thomporter/DwKZh/

    I also tried this:

    image

    • VR1256
      VR1256 over 6 years
      @Günter Zöchbauer can you help ?
    • Lazar Ljubenović
      Lazar Ljubenović over 6 years
      I hope you're not using "Angular 2" because it's the version from more than one year ago. The name of the framework is "Angular", not "Angular 2". It is currently in version 5, and a new version is released twice a year. Since it's mostly backward compatible, please do not specify the version number when asking broad questions.
    • VR1256
      VR1256 over 6 years
      Yes I am not using angular 2, since i am used to this version i mentioned that actually i am using angular version 5
  • Chris Sharp
    Chris Sharp over 6 years
    All of this code is unnecessary. It can easily be handled at the template level by restricting the input allowed into the field.
  • VR1256
    VR1256 over 6 years
    when I include this, it doesn't allow anything into textbox and copy paste using mouse still allows string values..
  • VR1256
    VR1256 over 6 years
    The fiddle i gave just works fine and handles in all scenarios but its in angular 1