Angular declarative library for handling hotkeys

In this post I am going to share an awesome angularjs declarative library for handling hotkeys in Angular applications. Web apps are getting closer and closer to be desktop-class applications. With this in mind, it makes sense to add hotkeys for those power users that are looking to navigate their favorite websites using hotkeys just as they do on their regular native apps. To help you have a better experience we developed Hotkeys.


Features

  • ✅ Support Element Scope
  • ✅ Support Global Listeners
  • ✅ Platform Agnostic
  • ✅ Hotkeys Cheatsheet

Installation

npm install @ngneat/hotkeys

Usage

Add HotkeysModule in your AppModule:

import { HotkeysModule } from '@ngneat/hotkeys';

@NgModule({
  imports: [HotkeysModule]
})
export class AppModule {}

Now you have two ways to start adding shortcuts to your application:

Hotkeys Directive

<input hotkeys="meta.a" (hotkey)="handleHotkey($event)" />

Hotkeys take care of transforming keys from macOS to Linux and Windows and vice-versa.

Additionally, the directive accepts three more inputs:

  • hotkeysGroup – define the group name.
  • hotkeysDescription – add a description.
  • hotkeysOptions – See Options

For example:

<input hotkeys="meta.n" 
      hotkeysGroup="File" 
      hotkeysDescription="New Document" 
      (hotkey)="handleHotkey($event)"

Hotkeys Service

This is a global service that can be injected anywhere:

import { HotkeysService } from '@ngneat/hotkeys';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private hotkeys: HotkeysService) {}

  ngOnInit() {
    this.hotkeys.addShortcut({ keys: 'meta.a' }).subscribe(e => console.log('Hotkey', e));
  }
}

Options

There are additional properties we can provide:

interface Options {
  // The group name
  group: string;
  // hotkey target element (defaults to `document`)
  element: HTMLElement;
  // The type of event (defaults to `keydown`)
  trigger: 'keydown' | 'keyup';
  // Allow input, textarea and select as key event sources (defaults to []).
  // It can be 'INPUT', 'TEXTAREA' or 'SELECT'.
  allowIn: AllowInElement[];
  // hotkey description
  description: string;
  // Included in the shortcut list to be display in the help dialog (defaults to `true`)
  showInHelpMenu: boolean;
  // Whether to prevent the default behavior of the event. (defaults to `true`)
  preventDefault: boolean;
}

onShortcut

Listen to any registered hotkey. For example:

const unsubscribe = this.hotkeys.onShortcut((event, key, target) => console.log('callback', key));

// When you're done listening, unsubscribe
unsubscribe();

registerHelpModal

Display a help dialog listing all visible hotkeys:

import { MatDialog } from '@angular/material/dialog';
import { HotkeysHelpComponent, HotkeysService } from '@ngneat/hotkeys';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  constructor(private hotkeys: HotkeysService, private dialog: MatDialog) {}

  ngAfterViewInit() {
    this.hotkeys.registerHelpModal(() => {
      const ref = this.dialog.open(HotkeysHelpComponent, { width: '500px' });
      ref.componentInstance.dimiss.subscribe(() => ref.close());
    });
  }
}

It accepts a second input that allows defining the hotkey that should open the dialog. The default shortcut is Shift + ?. Here’s how HotkeysHelpComponent looks like:

You can also provide a custom component. To help you with that, the service exposes the getShortcuts method.

removeShortcuts

Remove previously registered shortcuts.

// Remove a single shortcut
this.hotkeys.removeShortcuts('meta.a');
// Remove several shortcuts
this.hotkeys.removeShortcuts(['meta.1', 'meta.2']);

Hotkeys Shortcut Pipe

The hotkeysShortcut formats the shortcuts when presenting them in a custom help screen:

<div class="help-dialog-shortcut-key">
  <kbd [innerHTML]="hotkey.keys | hotkeysShortcut"></kbd>
</div>

The pipe accepts and additional parameter the way key combinations are separated. By default, the separator is +. In the following example, a - is used as separator.

<div class="help-dialog-shortcut-key">
  <kbd [innerHTML]="hotkey.keys | hotkeysShortcut: '-'"></kbd>
</div>

Allowing hotkeys in form elements

By default, the library prevents hotkey callbacks from firing when their event originates from an input, select, or textarea element. To enable hotkeys in these elements, specify them in the allowIn parameter:

import { HotkeysService } from '@ngneat/hotkeys';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private hotkeys: HotkeysService) {}

  ngOnInit() {
    this.hotkeys
      .addShortcut({ keys: 'meta.a', allowIn: ['INPUT', 'SELECT', 'TEXTAREA'] })
      .subscribe(e => console.log('Hotkey', e));
  }
}

It’s possible to enable them in the template as well:

<input hotkeys="meta.n" 
      hotkeysGroup="File" 
      hotkeysDescription="New Document" 
      hotkeysOptions="{allowIn: ['INPUT','SELECT', 'TEXTAREA']}" 
      (hotkey)="handleHotkey($event)"

See live demo and download source code.

Don’t forget to Subscribe My Public Notebook for more useful free scripts, tutorials and articles.

This awesome script developed by ngneat. Visit their official repository for more information and follow for future updates.