Skip to content

Instantly share code, notes, and snippets.

@nitin-rachabathuni
Created July 5, 2021 17:59
Show Gist options
  • Save nitin-rachabathuni/7137475c1fbc9864419cf9aa3fe463ce to your computer and use it in GitHub Desktop.
Save nitin-rachabathuni/7137475c1fbc9864419cf9aa3fe463ce to your computer and use it in GitHub Desktop.
Angular 10 numbers only input Directive
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appNumbersOnly]'
})
export default class NumbersOnlyDirective {
// Only want positive integers
private regex: RegExp = new RegExp(/^[+]?([1-9]+(?:[\.][0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$/);
// 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