Answers:
我会在您的组件中使用@HostListener装饰器:
import { HostListener } from '@angular/core';
@Component({
...
})
export class AppComponent {
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.key = event.key;
}
}
还有其他选项,例如:
主机属性内@Component
装饰
Angular建议@HostListener
在主机属性上使用装饰器https://angular.io/guide/styleguide#style-06-03
@Component({
...
host: {
'(document:keypress)': 'handleKeyboardEvent($event)'
}
})
export class AppComponent {
handleKeyboardEvent(event: KeyboardEvent) {
console.log(event);
}
}
renderer.listen
import { Component, Renderer2 } from '@angular/core';
@Component({
...
})
export class AppComponent {
globalListenFunc: Function;
constructor(private renderer: Renderer2) {}
ngOnInit() {
this.globalListenFunc = this.renderer.listen('document', 'keypress', e => {
console.log(e);
});
}
ngOnDestroy() {
// remove listener
this.globalListenFunc();
}
}
Observable.fromEvent
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/fromEvent';
import { Subscription } from 'rxjs/Subscription';
@Component({
...
})
export class AppComponent {
subscription: Subscription;
ngOnInit() {
this.subscription = Observable.fromEvent(document, 'keypress').subscribe(e => {
console.log(e);
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
esc
密钥,请使用keyup
事件。感谢@TroelsLarsen
function-key
(F1,F2,F3,...)?
yurzui的答案对我不起作用,可能是其他RC版本,或者对我而言可能是一个错误。无论哪种方式,这都是我对Angular2 RC4中的组件(现在已经过时)进行的操作。
@Component({
...
host: {
'(document:keydown)': 'handleKeyboardEvents($event)'
}
})
export class MyComponent {
...
handleKeyboardEvents(event: KeyboardEvent) {
this.key = event.which || event.keyCode;
}
}
keydown
的不是keypress
如果要在任何特定的键盘按钮按下时执行任何事件,在这种情况下,可以使用@HostListener。为此,您必须在组件ts文件中导入HostListener。
从“ @ angular / core”导入{HostListener};
然后在组件ts文件中的任何位置使用下面的函数。
@HostListener('document:keyup', ['$event'])
handleDeleteKeyboardEvent(event: KeyboardEvent) {
if(event.key === 'Delete')
{
// remove something...
}
}
请注意,不建议使用“ document:keypress”。我们应该改用document:keydown。
链接:https://developer.mozilla.org/fr/docs/Web/API/Document/keypress_event
我认为这做得最好
https://angular.io/api/platform-browser/EventManager
例如在app.component中
constructor(private eventManager: EventManager) {
const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
'document',
'keypress',
(ev) => {
console.log('ev', ev);
}
);
}
window:keypress
吗?