角度2 HostListener 按键检测转义键?

我使用以下方法来检测页面上的按键。我的计划是检测按下 Escape 键的时间,如果是,则运行一个方法。目前我只是尝试记录按下的键。但是从未检测到 Escape 键。

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

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);
}

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

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

Modern approach, event.key == "Escape"

The old alternatives (.keyCode and .which) are Deprecated.

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

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.

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

In my case (with Angular 10) keydown.escape works fine to track event escape by console.log():

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

But Angular change detector work fine only with keyup.escape.