What is Angular2 way of creating global keyboard shortcuts (a.k.a. hotkeys)?
You can use this syntax in your template
<div (window:keydown)="doSomething($event)">click me<div>
to call this method in your component
doSomething($event) {
// read keyCode or other properties
// from event and execute a command
}
To listen on the host component itself
@Component({
selector: 'app-component',
host: { '(window:keydown)': 'doSomething($event)' },
})
class AppComponent {
doSomething($event) {
...
}
}
or by this equivalent syntax
@Component({
selector: 'app-component',
})
class AppComponent {
@HostListener('window:keydown', ['$event'])
doSomething($event) {
...
}
}
You can use a library I created called angular2-hotkeys
It lets you create hotkeys like this:
constructor(private _hotkeysService: HotkeysService) {
this._hotkeysService.add(new Hotkey('meta+shift+g', (event: KeyboardEvent) => {
console.log('Typed hotkey');
return false; // Prevent bubbling
})); }