Created
September 8, 2021 17:16
-
-
Save JPaulDuncan/21c1d5f505e46d17e1ccc9c931808d93 to your computer and use it in GitHub Desktop.
Angular Directive: Digits Only
This file contains hidden or 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, 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