Listening for key events in angular

event.keyCode has been deprecated

You can use event.key instead

    @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    if(event.key == 'ArrowDown'){
      // Your row selection code
      console.log(event.key);
    }
  }

You will get the keyup event from the HostListener decorator. For every keyup event there is a keycode associate with the event. You can use that keycode to distinguish between the down arrow key press among all the key events for other keys.

export class AppComponent {
  @HostListener('window:keyup', ['$event'])
  keyEvent(event: KeyboardEvent) {
    if(event.keyCode == KEY_CODE.DOWN_ARROW){
      // Your row selection code
      console.log(event);
    }
  }
}

export enum KEY_CODE {
    UP_ARROW = 38,
    DOWN_ARROW = 40,
    RIGHT_ARROW = 39,
    LEFT_ARROW = 37
}

Use the above code in the component where you are displaying the table. I used AppComponent just to demonstrate

Tags:

Angular