DEV Community

Cover image for How to set up hot keys in Angular
Adrian Matei
Adrian Matei

Posted on • Updated on • Originally published at

How to set up hot keys in Angular

You know how good ideas come out of the blue? Recently it hit me that I could access my bookmarks history and the pinned bookmarks on more easily with hot keys. So I rolled up my sleeves and implemented this feature. This post details how.

Hot Keys on demo

Source code for is available on Github

The whole magic happens in this piece of code:

import { Component, HostListener } from '@angular/core';

import 'styles.scss';
import { UserDataHistoryStore } from './core/user/';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { HotKeysDialogComponent } from './shared/history-dialog/hot-keys-dialog.component';
import { UserDataPinnedStore } from './core/user/';

export class AppComponent {

  url = '';
  innerWidth: any;
  constructor(private userDataHistoryStore: UserDataHistoryStore,
              private userDataPinnedStore: UserDataPinnedStore,
              private historyDialog: MatDialog) {
    this.innerWidth = 100;

  @HostListener('window:keydown.control.p', ['$event'])
  showPinned(event: KeyboardEvent) {
    const dialogConfig = new MatDialogConfig();

    dialogConfig.disableClose = false;
    dialogConfig.autoFocus = true;
    dialogConfig.width = this.getRelativeWidth(); = {
      bookmarks$: this.userDataPinnedStore.getPinnedBookmarks$(1),
      title: '<i class="fas fa-thumbtack"></i> Pinned'

    const dialogRef =, dialogConfig);
      data => {
        console.log('Dialog output:', data);
Enter fullscreen mode Exit fullscreen mode

and to be more precise in the following three lines of code:

  @HostListener('window:keydown.control.p', ['$event'])
  showPinned(event: KeyboardEvent) {
Enter fullscreen mode Exit fullscreen mode

The HostListener1 decorator declares a DOM event to listen for. Angular will invoke the showPinned() method when the host emits the key-press event - Ctrl + P.

The event.preventDefault()2 method stops the default action of an element from happening, which in this case on Windows would be print the page, and instead launches an Angular dialog with the pinned bookmarks.

The same mechanism applies for the Ctrl + H shortcut to show the bookmarks from History.


I've told you it wasn't much, but it's definetely a piece of code I will bookmark for later.




Top comments (0)