Angular 2 HostListener keypress detect escape key?

2020-02-18 02:56发布

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

5条回答
兄弟一词,经得起流年.
2楼-- · 2020-02-18 03:41

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();
   }
查看更多
看我几分像从前
3楼-- · 2020-02-18 03:44

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);
}
查看更多
男人必须洒脱
4楼-- · 2020-02-18 03:47

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) {
    // ...
}
查看更多
成全新的幸福
5楼-- · 2020-02-18 03:52
姐就是有狂的资本
6楼-- · 2020-02-18 03:54

Modern approach

@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
    if (event.key === "Escape") {
        // Do things
    }
}
查看更多
登录 后发表回答