-
-
Save luisfarfan/f0cdde2b4f7c94018ea6724989c7f535 to your computer and use it in GitHub Desktop.
Revisions
-
ahmeti revised this gist
Apr 12, 2018 . 1 changed file with 1 addition and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -1,4 +1,4 @@ # Angular 5 - Only Number Input, Only Number Decimal ### Allow Only Numbers [0-9] ```html -
ahmeti renamed this gist
Apr 12, 2018 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
ahmeti renamed this gist
Apr 12, 2018 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
ahmeti renamed this gist
Apr 12, 2018 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
ahmeti renamed this gist
Apr 12, 2018 . 1 changed file with 0 additions and 0 deletions.There are no files selected for viewing
File renamed without changes. -
ahmeti created this gist
Apr 12, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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(); } } } ```