How to Implement Keyboard Shortcuts for your Web Application

In order to increase the user productivity and efficiency while using your web application, you might ended up implementing some sort of keyboard shortcuts. This will enable the end user to use the keyboard to do some actions or to navigate to certain pages without the need to use the mouse.

Implementing keyboard shortcuts in Angular is pretty simple thing. Basically you will need to decorate your Angular event handler method with HostListener attribute.. yes, that’s it. Here is a code sample that will show how to let the user using F10 to save the record

import { Component, HostListener } from '@angular/core';
export class AppComponent {
constructor() {
}

@HostListener('window:keydown.f10', ['$event'])
showPinned(event: KeyboardEvent) {
   event.preventDefault();
   alert('F10 pressed');
   this.save();
}
@HostListener('window:keydown.control.p', ['$event'])
pinRecord(event: KeyboardEvent) {
   event.preventDefault();
   alert('Ctrl+P pressed');
   this.saveRecordIntoHistory();
}
save() {
   //Implement Saving Logic here.
}
saveRecordIntoHistory () {
   //Implement Saving Record into History Logic here.
}
}

References

I built this article based on below references

  1. https://angular.io/api/core/HostListener 
  2. https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault