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 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.
<div (keypress)="handleInput($event)" tabindex="1">
This question is related to
typescript
angular
keypress
key-bindings
yurzui's answer didn't work for me, it might be a different RC version, or it might be a mistake on my part. Either way, here's how I did it with my component in Angular2 RC4 (which is now quite outdated).
@Component({
...
host: {
'(document:keydown)': 'handleKeyboardEvents($event)'
}
})
export class MyComponent {
...
handleKeyboardEvents(event: KeyboardEvent) {
this.key = event.which || event.keyCode;
}
}
I think this does the best job
https://angular.io/api/platform-browser/EventManager
for instance in app.component
constructor(private eventManager: EventManager) {
const removeGlobalEventListener = this.eventManager.addGlobalEventListener(
'document',
'keypress',
(ev) => {
console.log('ev', ev);
}
);
}
Just to add to this in 2019 w Angular 8,
instead of keypress I had to use keydown
@HostListener('document:keypress', ['$event'])
to
@HostListener('document:keydown', ['$event'])
Working Stacklitz
If you want to perform any event on any specific keyboard button press, in that case, you can use @HostListener. For this, you have to import HostListener in your component ts file.
import { HostListener } from '@angular/core';
then use below function anywhere in your component ts file.
@HostListener('document:keyup', ['$event'])
handleDeleteKeyboardEvent(event: KeyboardEvent) {
if(event.key === 'Delete')
{
// remove something...
}
}
Be aware "document:keypress" is deprecated. We should use document:keydown instead.
Link: https://developer.mozilla.org/fr/docs/Web/API/Document/keypress_event
Source: Stackoverflow.com