Angular 2 HostListener按键检测转义键? [英] Angular 2 HostListener keypress detect escape key?
本文介绍了Angular 2 HostListener按键检测转义键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下方法检测页面上的按键。我的计划是检测何时按下Escape键并运行方法(如果是)。目前我只是想记录按下哪个键。但是,永远不会检测到Escape键。
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!');
}
}
推荐答案
尝试它用 keydown
或 keyup
事件来捕获 Esc
键。实质上,你可以用文件替换
: document:keypress
:keydown.escape
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);
}
这篇关于Angular 2 HostListener按键检测转义键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文