Angular 2 HostListener按键检测转义键?

时间:2017-02-20 15:48:16

标签: javascript angular escaping keypress

我使用以下方法检测页面上的按键。我的计划是检测何时按下Escape键并运行方法(如果是)。目前我只是想记录按下哪个键。但是,永远不会检测到Escape键。

@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
  console.log(event);
  let x = event.keyCode;
  if (x === 27) {
      console.log('Escape!');
  }
}

6 个答案:

答案 0 :(得分:55)

使用keydownkeyup事件尝试捕获Esc密钥。实质上,您可以将document:keypress替换为document:keydown.escape

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

答案 1 :(得分:29)

使用以下代码对我有用:

const ESCAPE_KEYCODE = 27;

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

或以较短的方式:

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

答案 2 :(得分:5)

现代方法

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

答案 3 :(得分:3)

keydown和keyup似乎有效:http://embed.plnkr.co/VLajGbWhbaUhCy3xss8l/

答案 4 :(得分:3)

在我的情况下(使用Angular 10),keydown.escape可以很好地通过console.log()跟踪事件escape

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

但是Angular变化检测器仅适用于keyup.escape

答案 5 :(得分:0)

使用@HostListener装饰器,Angular使此操作变得容易。这是一个接受事件名称作为参数的函数装饰器。当该事件在主机元素上触发时,它将调用关联的函数。

@HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: 
    KeyboardEvent) {
    this.closeBlade();
   }
相关问题