Javascript Angular 2 HostListener 按键检测转义键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42348837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:05:08  来源:igfitidea点击:

Angular 2 HostListener keypress detect escape key?

javascriptangularescapingkeypress

提问by Jeremy Parkhurst

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.

我正在使用以下方法来检测页面上的按键。我的计划是检测何时按下 Escape 键并在按下时运行一个方法。目前我只是试图记录按下了哪个键。但是,从未检测到 Escape 键。

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

回答by Sawant

Try it with a keydownor keyupevent to capture the Esckey. In essence, you can replace document:keypresswith document:keydown.escape:

尝试使用keydownorkeyup事件来捕获Esc密钥。本质上,您可以替换document:keypressdocument:keydown.escape

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

回答by Gaurav Pandvia

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

回答by Gibolt

Modern approach

现代方法

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

回答by Lucas Tétreault

keydown and keyup seem to work: http://embed.plnkr.co/VLajGbWhbaUhCy3xss8l/

keydown 和 keyup 似乎工作:http: //embed.plnkr.co/VLajGbWhbaUhCy3xss8l/

回答by Mei

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.

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

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