当我在角度中使用“ KeyboardEvent”使用“ key”而不是“ keyCode”时出现错误

时间:2019-10-11 06:47:59

标签: angular angular-directive



我正在尝试为输入字段(文本框)创建一个自定义指令,使其仅接受数字,而不接受字母字符。

我有以下文件(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)

This condition will always return 'false' since the types 'string' and '65' have no overlap. (screenshot)


所以我的问题是如何解决?

提前感谢

1 个答案:

答案 0 :(得分:1)

正如Eliseo所指出的,我使用了此解决方案,并且效果很好 https://stackoverflow.com/a/54462816/6663458

感谢Eliseo