Bileşeninizde @HostListener dekoratörünü kullanırdım :
import { HostListener } from '@angular/core';
@Component({
...
})
export class AppComponent {
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.key = event.key;
}
}
Aşağıdakiler gibi başka seçenekler de vardır:
@Component
dekoratör içinde barındırma özelliği
Angular @HostListener
, ana mülkün yerine dekoratör kullanılmasını önerir 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();
}
}
window:keypress
mi