You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Angular 5 - Only Number Input, Only Number Decimal
Allow Only Numbers [0-9]
<inputnumericnumericType="number" type="text">
Allow Numbers & Decimals [0-9] [also only one dot]
<inputnumericnumericType="decimal" type="text">
import{Directive,ElementRef,HostListener,Input}from'@angular/core';
@Directive({selector: '[numeric]'})exportclassNumericDirective{
@Input('numericType')numericType: string;// number | decimalprivateregex={number: newRegExp(/^\d+$/),decimal: newRegExp(/^[0-9]+(\.[0-9]*){0,1}$/g)};privatespecialKeys={number: ['Backspace','Tab','End','Home','ArrowLeft','ArrowRight'],decimal: ['Backspace','Tab','End','Home','ArrowLeft','ArrowRight'],};constructor(privateel: 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();}}}