6

In my application I am having a feature for a rendered list component where if I press either the left or the right arrow, wherever I am on the screen and whatever is selected, I navigate through its element and the list selection changes. To accomplish this I use the following code:

@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent): void {
  if (!this.isComparisonWindow) {
    if (event.keyCode === 37) {
      this.navigateLeft();
    } else if (event.keyCode === 39) {
      this.navigateRight();
    }
  }
}

which is pretty straightforward. The problem I encountered is that I receive the warning that

keyCode is deprecated. (deprecation) tslint(1)

and further research proved this to be true. But yet I couldn't find an alternative to keycode that easily fulfills the code above and works for Chrome, IE11, Firefox and preferably Safari also. Most answers provide either libraries or extra code that checks multiple cases instead of only one.

So I am asking, what is the current accepted alternative to keycode which works the same but isn't deprecated?

Artyomska
  • 1,309
  • 5
  • 26
  • 53
  • Does this answer your question? [How to detect escape key press with pure JS or jQuery?](https://stackoverflow.com/questions/3369593/how-to-detect-escape-key-press-with-pure-js-or-jquery) – adripanico Feb 11 '20 at 13:29

2 Answers2

12

Change it to this :

@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent): void {
  if (!this.isComparisonWindow) {
    if (event.key === 'ArrowLeft') {
      this.navigateLeft();
    } else if (event.key === 'ArrowRight') {
      this.navigateRight();
    }
  }
}
Oussail
  • 2,200
  • 11
  • 24
5

You can use .key or .code, they are widely supported now days

https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#Browser_compatibility

WSD
  • 3,243
  • 26
  • 38