Skip to content

Instantly share code, notes, and snippets.

@JPaulDuncan
Created September 8, 2021 17:16
Show Gist options
  • Select an option

  • Save JPaulDuncan/21c1d5f505e46d17e1ccc9c931808d93 to your computer and use it in GitHub Desktop.

Select an option

Save JPaulDuncan/21c1d5f505e46d17e1ccc9c931808d93 to your computer and use it in GitHub Desktop.
Angular Directive: Digits Only
import { Directive, ElementRef, HostListener, Input } from "@angular/core";
/**
* Ensures the associated element only allows digits to be entered.
* Allows for editing and in-element navigation.
*
* Usage: digitOnly allowSpaces="false"
*/
@Directive({
selector: "[digitOnly]"
})
export class DigitOnlyDirective {
private navigationKeys = [
"Backspace",
"Delete",
"Tab",
"Escape",
"Enter",
"Home",
"End",
"ArrowLeft",
"ArrowRight",
"Clear",
"Copy",
"Paste"
];
private allowedEditKeys = ["a", "c", "v", "x"];
inputElement: HTMLElement;
@Input() allowSpaces: boolean = false;
constructor(public element: ElementRef) {
this.inputElement = element.nativeElement;
}
@HostListener("keydown", ["$event"])
onKeyDown(event: KeyboardEvent) {
const isNavigation = this.navigationKeys.find((key) => key === event.key);
const isEdit = ((event.ctrlKey || event.metaKey) && this.allowedEditKeys.find((key) => key === event.key));
if (isNavigation || isEdit) { return; };
if (isNaN(Number(event.key))) { event.preventDefault(); }
if (!this.allowSpaces && event.key === " ") { event.preventDefault(); }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment