Created
July 5, 2021 17:59
-
-
Save nitin-rachabathuni/7137475c1fbc9864419cf9aa3fe463ce to your computer and use it in GitHub Desktop.
Angular 10 numbers only input Directive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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