Skip to content

Instantly share code, notes, and snippets.

@rajaramtt
Created September 12, 2019 17:48
Show Gist options
  • Save rajaramtt/5695602518d4bcb63aeef19a17a7e235 to your computer and use it in GitHub Desktop.
Save rajaramtt/5695602518d4bcb63aeef19a17a7e235 to your computer and use it in GitHub Desktop.
import { Directive, Input, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appNumbersOnly]'
})
export class NumbersOnlyDirective {
@Input() fieldMaxLength: number;
constructor(private _el: ElementRef) { }
@HostListener('keypress', ['$event']) onkeypress(event) {
const initalValue = this._el.nativeElement.value;
if (this.fieldMaxLength) {
if ((initalValue.length + 1) > this.fieldMaxLength) {
event.preventDefault();
}
}
if (event.code === 'KeyE' || event.code === 'Period') {
event.preventDefault();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment