Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nitin-rachabathuni/3ce78fa400ac9aecf865234d65199dea to your computer and use it in GitHub Desktop.
Save nitin-rachabathuni/3ce78fa400ac9aecf865234d65199dea to your computer and use it in GitHub Desktop.
Angular 6 Directive to allow only positive integers in an input
// *** NOTE: This is only allowing positive integers, adjust the regex to suit your needs
// Stackblitz (w/ Angular Material): https://stackblitz.com/edit/angular-8fsecv?file=app%2Fnumber-only.directive.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[numberOnly]'
})
export class NumberOnlyDirective {
// Only want positive integers
private regex: RegExp = new RegExp(/^\d+$/g);
// Allow key codes for special events Backspace, tab, end, home
private specialKeys = ['Backspace', 'Tab', 'End', 'Home'];
constructor(private el: ElementRef) { }
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) >= -1) {
return;
}
let current: string = this.el.nativeElement.value;
let next: string = current.concat(event.key);
if (next && !String(next).match(this.regex)) {
event.preventDefault();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment