Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: keyCode is deprecated [duplicate]

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?

like image 500
Artyomska Avatar asked Dec 08 '22 10:12

Artyomska


2 Answers

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();
    }
  }
}
like image 113
Oussail Avatar answered Dec 23 '22 03:12

Oussail


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

like image 35
guzmanoj Avatar answered Dec 23 '22 03:12

guzmanoj