Angular 2 Tutorial: Adding HotKeys (Keyboard shortcuts) to a Component

Arguably hotkeys can substantially increase the usability of an application, the less the users have to touch the mouse the better will be their experience with the application.

Luckily for us there is a very easy way of defining hotkeys on angular2, which is by adding a listener to the host component, we can accomplish this by just adding the element host to the @Component decorator.

Let’s take a look at an example:

import {Component } from '@angular/core';
 
@Component({
  selector: 'hotkeys-app',
  host: {'(window:keydown)': 'hotkeys($event)'},
  template: `
  	<button (click)=showMessage()>Hotkey Test</button>
  `,
})
export class AppComponent { 
 
   hotkeys(event){
      if (event.keyCode == 65){
         this.showMessage();
      }
   }
 
   showMessage(){
      alert('Hotkey Test');
   }
}

As you can see I’ve used the element host to add a listener to the window:keydown event, it will call the function hotkeys(event) every time this event occurs, all we have to do now on this function is to determine which key was pressed and take actions accordingly.

As an example I’ve placed a button on the template, let’s suppose we want the action of this button, which is the showMessage() funtion, to execute when the user presses the letter 'a' on the keyboard. On the hotkeys function we have the event parameter containing the keyCode, we have to check this value to see which key was pressed, in this case I’m calling showMessage() when the keycode is 65 (which is code for the letter 'a').

It’s also very common to use combinations as hotkeys, like for example ctrl+a. To do that we just have to change our condition a little bit:

if (event.keyCode == 65 && event.ctrlKey){

The only diference is that besides checking the keyCode I’m also using the event.ctrlKey to check if the ctrl key is pressed.

That’s it guys! Just leave a comment if you have any doubts.

3 comments on “Angular 2 Tutorial: Adding HotKeys (Keyboard shortcuts) to a Component

Leave a Reply to andy Cancel reply

Your email address will not be published. Required fields are marked *

Obs: Use the tag <pre lang="LANGUAGE"> to include code blocks to your comment.
Example: <pre lang="javascript"> console.log('Test'); </pre>