Angular 2 HostListener如何检测按下Esc键?

104
我正在使用以下方法检测页面上的按键。 我的计划是检测当按下Escape键时运行一个方法。 目前,我只尝试记录按下的键。 然而,永远不会检测到Escape键。
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
  console.log(event);
  let x = event.keyCode;
  if (x === 27) {
      console.log('Escape!');
  }
}
6个回答

213

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

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

1
谢谢兄弟,你让我今天过得很愉快! - Shailesh Ladumor
为了决定使用哪个关键事件,请查看此SO答案:https://dev59.com/KlsW5IYBdhLWcg3wI0RH#46403258 - Sagar
2
事件规范是如何工作的?document:keydown.escape似乎相当武断。是否有关于有效语法的文档?我甚至无法在Angular的HostListener指令功能中找到正确的实现,监听器似乎深藏在内部。 - Martin Nyolt
如果这个不起作用,请尝试使用“window:keydown.espace”。 - Egor Pavlikhin
现在应该是 Escape,而不是 escape - Udhayakumar

43

我使用以下代码可以正常工作:

const ESCAPE_KEYCODE = 27;

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

或者更简洁地说:

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

4
请注意,KeyCode正在被弃用(deprecated),您可以使用event.key代替,并匹配字符串“Escape”。无需使用代码,这会使代码更易于阅读。 - Tony
1
很好的 document:keydown.escape,所以我们不需要进行 27 检查。谢谢。 - LeOn - Han Li

32

现代方法,event.key == "Escape"

旧的方案(.keyCode.which)已被弃用。

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

2
在IE 11中无法工作,其中键被称为“Esc”:if (event.key ===“Escape”|| event.key ===“Esc”) - akcasoy
2
不错的发现!但公平地说,标题是“现代”:D - Gibolt
2
我在使用带有Angular组件的条形码扫描仪时,一直无法稳定地捕获字符代码13(回车键)。改为使用keydown解决了这个问题。 - James Blake

11

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

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

但是 Angular 变更检测器仅与 keyup.escape 配合使用才能正常工作。


2
我需要将这个 @HostListener('document:keydown.escape') 做出来才能让它工作,受到 @Gibolt 的启发。 - hughjdavey

5

Angular使用@HostListener装饰器来实现这一点。这是一个函数装饰器,接受一个事件名称作为参数。当该事件在宿主元素上触发时,它会调用相关联的函数。

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

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接