I'm getting an error when I use “key” instead of “keyCode” with “KeyboardEvent” in angular

淺唱寂寞╮ 提交于 2021-01-27 18:41:49

问题




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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!