Angular 2 HostListener keypress detect escape key?

97,353

Solution 1

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

Solution 2

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) {
    // ...
}

Solution 3

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

Solution 4

In my case (with Angular 10) keydown.escape works fine to track event escape by console.log():

@HostListener('keydown.escape')
fn() {
 console.log();
}

But Angular change detector work fine only with keyup.escape.

Solution 5

Angular makes this easy with the @HostListener decorator. This is a function decorator that accepts an event name as an argument. When that event gets fired on the host element it calls the associated function.

@HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: 
    KeyboardEvent) {
    this.closeBlade();
   }
Share:
97,353
Jeremy P
Author by

Jeremy P

Fresh out of college and now finding my place in the wondrous world of computer science and technology!

Updated on July 08, 2022

Comments

  • Jeremy P
    Jeremy P almost 2 years

    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!');
      }
    }
    
  • Shailesh Ladumor
    Shailesh Ladumor about 7 years
    Thanks bro. you made my day!
  • Sagar
    Sagar almost 7 years
    To decide which one of the key events to use, check this SO answer: stackoverflow.com/a/46403258/3380547
  • Tony
    Tony over 6 years
    Note that KeyCode is being deprecated, you can replace with event.key and match against the string "Escape". No need to use codes, having the side effect of making the code easy to read.
  • LeOn - Han Li
    LeOn - Han Li almost 6 years
    Nice document:keydown.escape so we do not need to do that 27 check. Thanks.
  • akcasoy
    akcasoy almost 6 years
    Doesn't work in IE 11, where the key is called "Esc": if (event.key === "Escape" || event.key === "Esc")
  • Gibolt
    Gibolt almost 6 years
    Good catch! To be fair though, the title is 'Modern' :D
  • Martin Nyolt
    Martin Nyolt over 5 years
    How does the event specification work? document:keydown.escape seems rather arbitrary. Is there any documentation on the valid syntax? I could not even find a proper implementation in Angular of the HostListener directive functionality, the listeners seem to be buried deep in the internals.
  • James Blake
    James Blake almost 5 years
    I was having problems consistently capturing char code 13 (enter key) when using a barcode scanner with an angular component. Changing from keypress to keydown resolved this for me.
  • Egor Pavlikhin
    Egor Pavlikhin over 3 years
    If this doesn't work, try 'window:keydown.espace' instead.
  • Udhayakumar
    Udhayakumar about 2 years
    escape should be Escape now
  • hughjdavey
    hughjdavey about 2 years
    I needed to make this @HostListener('document:keydown.escape') for it to work, inspired by @Gibolt