2

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

3
  • @Günter Zöchbauer can you help ? Commented Dec 13, 2017 at 19:32
  • 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. Commented Dec 13, 2017 at 19:34
  • Yes I am not using angular 2, since i am used to this version i mentioned that actually i am using angular version 5 Commented Dec 13, 2017 at 19:36

3 Answers 3

6

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">
    
Sign up to request clarification or add additional context in comments.

Comments

6

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, ''));
  }
}

Comments

0

your directive code should have this

@HostListener("keypress",['$event']) onKeyPress(e){
        var char=e.char;
        var regExp = new RegExp(/[0-9.]/);
        if (regExp.test(char)) 
            return true
        else
            return false;
    }

3 Comments

All of this code is unnecessary. It can easily be handled at the template level by restricting the input allowed into the field.
when I include this, it doesn't allow anything into textbox and copy paste using mouse still allows string values..
The fiddle i gave just works fine and handles in all scenarios but its in angular 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.