What would be proper way of creating global keyboard shortcuts (a.k.a. hotkeys) in Angular2 application?
Let's say good starting point would be to get working: "?" for cheat-sheet and "Alt+s" for submitting form.
Should I map "?" somehow to main component and then develop attribute directive that would be applied to those components which should respond on particular hotkeys, but then - how do I prevent input fields from responding to "?".
A global hot key is associated with a particular nonchild window. It allows the user to activate the window from any part of the system. An application sets a global hot key for a particular window by sending the WM_SETHOTKEY message to that window.
Keyboard shortcuts are generally used to expedite common operations by reducing input sequences to a few keystrokes, hence the term "shortcut". To differentiate from general keyboard input, most keyboard shortcuts require the user to press and hold several keys simultaneously or a sequence of keys one after the other.
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
})); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With