Skip to content

Instantly share code, notes, and snippets.

@uzbekdev1
Forked from ahmeti/only-number.directive.md
Created April 9, 2019 10:55
Show Gist options
  • Save uzbekdev1/e80250e08ac6e8a50c9a5e2e68a05df3 to your computer and use it in GitHub Desktop.
Save uzbekdev1/e80250e08ac6e8a50c9a5e2e68a05df3 to your computer and use it in GitHub Desktop.
Angular 5 - Only Number Input, Only Number Decimal

Angular 5 - Only Number Input, Only Number Decimal

Allow Only Numbers [0-9]

<input numeric numericType="number" type="text">

Allow Numbers & Decimals [0-9] [also only one dot]

<input numeric numericType="decimal" type="text">
import {Directive, ElementRef, HostListener, Input} from '@angular/core';

@Directive({
    selector: '[numeric]'
})

export class NumericDirective {

    @Input('numericType') numericType: string; // number | decimal

    private regex = {
        number: new RegExp(/^\d+$/),
        decimal: new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g)
    };

    private specialKeys = {
        number: [ 'Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight' ],
        decimal: [ 'Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight' ],
    };

    constructor(private el: ElementRef) {
    }

    @HostListener('keydown', [ '$event' ])
    onKeyDown(event: KeyboardEvent) {

        if (this.specialKeys[this.numericType].indexOf(event.key) !== -1) {
            return;
        }
        // Do not use event.keycode this is deprecated.
        // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
        let current: string = this.el.nativeElement.value;
        let next: string = current.concat(event.key);
        if (next && !String(next).match(this.regex[this.numericType])) {
            event.preventDefault();
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment