numberonlydirective.ts 698 Bytes
import { Directive, ElementRef, Input, Output, OnChanges, EventEmitter, HostListener, SimpleChanges
} from '@angular/core';

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

export class NumberOnlyDirective {

   constructor(private el: ElementRef) { }

    @HostListener('keyup', [ '$event' ])
        onKeyUp(event: KeyboardEvent) {
            var keyValue = parseInt(event.key);
            if ([46, 8, 9, 27, 13].indexOf(event.keyCode) !== -1) {
                return;
            }
            if(isNaN(keyValue)) {
                this.el.nativeElement.value = 
                (<HTMLInputElement>event.currentTarget)
                .value.replace(/[^0-9]/g, '');
            }
        }
}