我正在尝试为输入字段(文本框)创建一个自定义指令,使其仅接受数字,而不接受字母字符。
我有以下文件(only-numbers.directive.ts):
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();
}
}
}
上面的代码可以正常工作,但是我知道“ keyCode ”已被弃用,因此我尝试使用“ key ”代替,但是我明白了错误:
Argument of type 'string' is not assignable to parameter of type 'number'. (screenshot)
所以我的问题是如何解决?
提前感谢
答案 0 :(得分:1)
正如Eliseo所指出的,我使用了此解决方案,并且效果很好 https://stackoverflow.com/a/54462816/6663458
感谢Eliseo