typescript 70 lines · 9 steps

A keyboard shortcut directive in Angular

A standalone attribute directive listens for global keystrokes and emits an event when a configured combo matches.

Explained by highlit
1import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
2 
3interface Shortcut {
4 key: string;
5 ctrl?: boolean;
6 shift?: boolean;
7 alt?: boolean;
8 meta?: boolean;
9}
10 
11@Directive({
12 selector: '[appKeyboardShortcut]',
13 standalone: true,
14})
15export class KeyboardShortcutDirective {
16 @Input('appKeyboardShortcut') shortcut!: Shortcut | string;
17 @Input() allowInInputs = false;
18 @Output() triggered = new EventEmitter<KeyboardEvent>();
19 
20 @HostListener('document:keydown', ['$event'])
21 onKeyDown(event: KeyboardEvent): void {
22 if (!this.allowInInputs && this.isEditableTarget(event.target)) {
23 return;
24 }
25 
26 if (!this.matches(event)) {
27 return;
28 }
29 
30 event.preventDefault();
31 event.stopPropagation();
32 this.triggered.emit(event);
33 }
34 
35 private matches(event: KeyboardEvent): boolean {
36 const spec = this.normalize(this.shortcut);
37 return (
38 event.key.toLowerCase() === spec.key.toLowerCase() &&
39 event.ctrlKey === !!spec.ctrl &&
40 event.shiftKey === !!spec.shift &&
41 event.altKey === !!spec.alt &&
42 event.metaKey === !!spec.meta
43 );
44 }
45 
46 private normalize(shortcut: Shortcut | string): Shortcut {
47 if (typeof shortcut !== 'string') {
48 return shortcut;
49 }
50 
51 const parts = shortcut.toLowerCase().split('+').map((p) => p.trim());
52 const key = parts.pop() ?? '';
53 return {
54 key,
55 ctrl: parts.includes('ctrl'),
56 shift: parts.includes('shift'),
57 alt: parts.includes('alt'),
58 meta: parts.includes('meta') || parts.includes('cmd'),
59 };
60 }
61 
62 private isEditableTarget(target: EventTarget | null): boolean {
63 const el = target as HTMLElement | null;
64 if (!el) {
65 return false;
66 }
67 const tag = el.tagName;
68 return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || el.isContentEditable;
69 }
70}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Directives can bind to document-level events with HostListener to capture input anywhere on the page.
  2. 2Accepting either a string or an object and normalizing it internally gives callers a flexible, forgiving API.
  3. 3Guarding against editable targets prevents shortcuts from hijacking normal typing in forms.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A keyboard shortcut directive in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code