Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 HostListener keypress detect escape key?

I am using the following method to detect keypresses on a page. My plan is to detect when the Escape key is pressed and run a method if so. For the moment I am just attempting to log which key is pressed. However the Escape key is never detected.

@HostListener('document:keypress', ['$event']) handleKeyboardEvent(event: KeyboardEvent) {   console.log(event);   let x = event.keyCode;   if (x === 27) {       console.log('Escape!');   } } 
like image 457
Jeremy P Avatar asked Feb 20 '17 15:02

Jeremy P


1 Answers

Try it with a keydown or keyup event to capture the Esc key. In essence, you can replace document:keypress with document:keydown.escape:

@HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: KeyboardEvent) {     console.log(event); } 
like image 149
Sawant Avatar answered Oct 06 '22 00:10

Sawant