I made a directive to prevent specific input, similar to others posted here and in other posts. I based mine in this article, but made a few changes to avoid using the deprecated keyCode
attribute, among other things.
I also lifted the restriction on the allowed keyboard commands (any combination of keys containing Ctrl
, Command
, Shift
or Alt
) because it may lead to unintended restrictions (like being unable to execute the undo/redo command).
Here is the directive:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[inputDigitsOnly]',
})
export class InputDigitsOnlyDirective {
private static readonly allowedKeyCodes = [
"Backspace",
"Delete",
"Insert",
"ArrowUp",
"ArrowRight",
"ArrowDown",
"ArrowLeft",
"Tab",
"Home",
"End",
"Enter",
"Digit1",
"Digit2",
"Digit3",
"Digit4",
"Digit5",
"Digit6",
"Digit7",
"Digit8",
"Digit9",
"Digit0",
"Numpad0",
"Numpad1",
"Numpad2",
"Numpad3",
"Numpad4",
"Numpad5",
"Numpad6",
"Numpad7",
"Numpad8",
"Numpad9",
];
@HostListener('keydown', ['$event'])
onKeyDown(e: KeyboardEvent) {
// This condition checks whether a keyboard control key was pressed.
// I've left this 'open' on purpose, because I don't want to restrict which commands
// can be executed in the browser. For example, It wouldn't make sense for me to prevent
// a find command (Ctrl + F or Command + F) just for having the focus on the input with
// this directive.
const isCommandExecution = e.ctrlKey || e.metaKey || e.shiftKey || e.altKey;
const isKeyAllowed = InputDigitsOnlyDirective.allowedKeyCodes.indexOf(e.code) !== -1;
if (!isCommandExecution && !isKeyAllowed) {
e.preventDefault();
return; // let it happen, don't do anything
}
}
}
Then you just need to add the directive in the input:
<input type="text" inputDigitsOnly>
You can change it to fit your needs. You can check the list of available key codes here.
Hope it helps.