我使用以下方法来检测页面上的按键.我的计划是检测何时按下Escape键并运行方法(如果是).目前我只是想记录按下哪个键.但是,永远不会检测到Escape键.
@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替换为document:keydown.escape:
@HostListener('document:keydown.escape', ['$event']) onKeydownHandler(event: KeyboardEvent) {
console.log(event);
}