如何检测Angular 2中的任何按键?

Yah*_*din 7 dom-events angular

如何检测Angular 2上的任何按键(例如,不一定在输入框中)

目前我设法使用以下代码执行此操作:

import {Component, HostListener} from "@angular/core";

@Component(<any>{
    selector: 'foo',
    template: `<h1>Foo</h1>`,
})
export class FooComponent {
    @HostListener('document:keypress', ['$event'])
    keypress(e: KeyboardEvent) {
        console.log("Key Up! " + e.key);
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码设法适用于大多数字符,例如字母数字,标点符号,符号等

问题是当按下SHIFT,CTRL,F1 ... F12,Tab,ALT等键时,此方法不会运行.

小智 7

你必须使用('document:keydown')而不是('document:keypress')得到转移,ctrl ...