Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hostlistener does not respond to arrow keys

Tags:

angular

I have an angular 2 component and in the middle of that I listen for keys:

  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
      console.log(event);
  }

I'm not getting any notification of arrow keys, enter keys work, as do normal keys.

I've read in this post that I can add a window.event:

Angular2 Navigation using Arrow Keys That seems to be the only post on the subject.

Whilst I can use that solution (and admittedly I'm sure it would work), it doesn't seem very "angular" to me. Also what element should I put this on?

Why am I not getting notification of arrow keys? They are a keypress aren't they?

like image 669
PeterS Avatar asked May 19 '17 16:05

PeterS


1 Answers

You'd need to use keydown for arrow keys.

@HostListener('document:keydown', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
      console.log(event);
  }

keypress event represents a character being typed, and arrows are not characters so they won't trigger keypress

like image 137
Milad Avatar answered Sep 24 '22 21:09

Milad