问题
I'm trying to create a custom directive for an input field (textbox) such that it accepts only numbers and not alphabetical characters.
I have the following (only-numbers.directive.ts) file:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: "[onlyNumbers]"
})
export class OnlyNumbersDirective {
constructor(private el: ElementRef) {}
@HostListener('keydown', ['$event'])
onKeyDown(e: KeyboardEvent) {
if (
// Allow: Delete, Backspace, Tab, Escape, Enter
[46, 8, 9, 27, 13].indexOf(e.keyCode) !== -1 ||
(e.keyCode === 65 && e.ctrlKey === true) || // Allow: Ctrl+A
(e.keyCode === 67 && e.ctrlKey === true) || // Allow: Ctrl+C
(e.keyCode === 86 && e.ctrlKey === true) || // Allow: Ctrl+V
(e.keyCode === 88 && e.ctrlKey === true) || // Allow: Ctrl+X
(e.keyCode === 65 && e.metaKey === true) || // Cmd+A (Mac)
(e.keyCode === 67 && e.metaKey === true) || // Cmd+C (Mac)
(e.keyCode === 86 && e.metaKey === true) || // Cmd+V (Mac)
(e.keyCode === 88 && e.metaKey === true) || // Cmd+X (Mac)
(e.keyCode >= 35 && e.keyCode <= 39) // Home, End, Left, Right
) {
return; // let it happen, don't do anything
}
// Ensure that it is a number and stop the keypress
if (
(e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&
(e.keyCode < 96 || e.keyCode > 105)
) {
e.preventDefault();
}
}
}
The code above works fine but I knew that the "keyCode" is deprecated, so I try to use "key" instead but I got this errors:
Argument of type 'string' is not assignable to parameter of type 'number'. (screenshot)
This condition will always return 'false' since the types 'string' and '65' have no overlap. (screenshot)
So my question is how do I fix it?
Thanks in advance
回答1:
I used this solution as Eliseo pointed out and it worked very well https://stackoverflow.com/a/54462816/6663458
Thanks Eliseo
来源:https://stackoverflow.com/questions/58335665/im-getting-an-error-when-i-use-key-instead-of-keycode-with-keyboardevent