Angular 2 HostListener Keypress Detect Escape Key?


Answer :

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); } 

It worked for me using the following code:

const ESCAPE_KEYCODE = 27;  @HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {     if (event.keyCode === ESCAPE_KEYCODE) {         // ...     } } 

or in shorter way:

@HostListener('document:keydown.escape', ['$event']) onKeydownHandler(evt: KeyboardEvent) {     // ... } 

Modern approach, event.key == "Escape"

The old alternatives (.keyCode and .which) are Deprecated.

@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {     if (event.key === "Escape") {         // Do things     } } 

Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable