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?
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();
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With