snippettypescriptangularCritical
How can I listen for keypress event on the whole page?
Viewed 0 times
pagehoweventwholetheforcanlistenkeypress
Problem
I'm looking for a way to bind a function to my whole page (when a user presses a key, I want it to trigger a function in my component.ts)
It was easy in AngularJS with a
I tried it with a div wrapper on the whole page but it doesn't seem to work.
it only works when the focus is on it.
It was easy in AngularJS with a
ng-keypress but it does not work with (keypress)="handleInput($event)". I tried it with a div wrapper on the whole page but it doesn't seem to work.
it only works when the focus is on it.
Solution
I would use @HostListener decorator within your component:
There are also other options like:
host property within
Angular recommends using
renderer.listen
Observable.fromEvent
import { HostListener } from '@angular/core';
@Component({
...
})
export class AppComponent {
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
this.key = event.key;
}
}
There are also other options like:
host property within
@Component decoratorAngular recommends using
@HostListener decorator over host property 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();
}
}
Context
Stack Overflow Q#37362488, score: 308
Revisions (0)
No revisions yet.