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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Directives can bind to document-level events with HostListener to capture input anywhere on the page.
- 2Accepting either a string or an object and normalizing it internally gives callers a flexible, forgiving API.
- 3Guarding against editable targets prevents shortcuts from hijacking normal typing in forms.
Related explainers
javascript
const STORAGE_KEY = "theme-preference"; function getSystemTheme() { return window.matchMedia("(prefers-color-scheme: dark)").matches
Building a dark-mode toggle that respects the OS
dark-mode
localstorage
matchmedia
Intermediate
8 steps
typescript
interface JwtPayload { exp?: number; iat?: number; sub?: string;
Decoding a JWT to check expiry
jwt
base64url
type-guards
Intermediate
8 steps
typescript
import { Component, computed, signal } from '@angular/core'; import { CdkTableModule } from '@angular/cdk/table'; import { CdkScrollableModule } from '@angular/cdk/scrolling';
Paginating a CDK table with Angular signals
signals
computed-state
pagination
Intermediate
9 steps
typescript
type Semver = { major: number; minor: number; patch: number;
Parsing and comparing semver strings in TypeScript
parsing
regular-expressions
comparison
Intermediate
9 steps
typescript
import { Component } from '@angular/core'; import { trigger, transition,
Staggered list animations in Angular
animations
stagger
enter-leave
Intermediate
10 steps
typescript
type Handler = (event: KeyboardEvent) => void; interface Binding { combo: string;
Building a keyboard shortcut manager in TypeScript
event-handling
normalization
closures
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-keyboard-shortcut-directive-in-angular-explained-typescript-aa57/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.