Skip to content

Instantly share code, notes, and snippets.

@luisfarfan
Forked from ahmeti/only-number.directive.md
Created February 8, 2019 16:48
Show Gist options
  • Save luisfarfan/f0cdde2b4f7c94018ea6724989c7f535 to your computer and use it in GitHub Desktop.
Save luisfarfan/f0cdde2b4f7c94018ea6724989c7f535 to your computer and use it in GitHub Desktop.

Revisions

  1. @ahmeti ahmeti revised this gist Apr 12, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion only-number.directive.md
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,4 @@
    # Angular 5
    # Angular 5 - Only Number Input, Only Number Decimal

    ### Allow Only Numbers [0-9]
    ```html
  2. @ahmeti ahmeti renamed this gist Apr 12, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  3. @ahmeti ahmeti renamed this gist Apr 12, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  4. @ahmeti ahmeti renamed this gist Apr 12, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  5. @ahmeti ahmeti renamed this gist Apr 12, 2018. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  6. @ahmeti ahmeti created this gist Apr 12, 2018.
    52 changes: 52 additions & 0 deletions only-number.directive.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,52 @@
    # Angular 5

    ### Allow Only Numbers [0-9]
    ```html
    <input numeric numericType="number" type="text">
    ```

    ### Allow Numbers & Decimals [0-9] [also only one dot]
    ```html
    <input numeric numericType="decimal" type="text">
    ```

    ```javascript
    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();
    }
    }
    }
    ```