Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Angular2 way of creating global keyboard shortcuts (a.k.a. hotkeys)?

Tags:

angular

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 "?".

like image 604
Andris Krauze Avatar asked Feb 24 '16 11:02

Andris Krauze


People also ask

What are global hotkeys?

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.

What are keyboard shortcuts used for?

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.


2 Answers

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) {
    ...
  }
}
like image 147
Günter Zöchbauer Avatar answered Oct 12 '22 13:10

Günter Zöchbauer


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
}));  }
like image 23
Nick Richardson Avatar answered Oct 12 '22 15:10

Nick Richardson