You can use the @HostListener decorator to handle keydown events at the window level and match key combinations.
Keyboard Shortcut Directive
1. Create the Directive
import { Directive, HostListener, Input, Output, EventEmitter } from '@angular/core';
@Directive({
selector: '[appShortcut]'
})
export class ShortcutDirective {
@Input('appShortcut') keys: string = ''; // e.g., 'ctrl+shift+s'
@Output() shortcutTriggered = new EventEmitter<void>();
@HostListener('window:keydown', ['$event'])
handleKeydown(event: KeyboardEvent) {
const keyCombo = this.keys.toLowerCase().split('+');
const ctrl = keyCombo.includes('ctrl') ? event.ctrlKey : true;
const shift = keyCombo.includes('shift') ? event.shiftKey : true;
const alt = keyCombo.includes('alt') ? event.altKey : true;
const key = keyCombo.find(k => !['ctrl', 'shift', 'alt'].includes(k)) === event.key.toLowerCase();
if (ctrl && shift && alt && key) {
event.preventDefault();
this.shortcutTriggered.emit();
}
}
}
2. Use in Template
<!-- Example: Ctrl + Shift + S triggers this shortcut -->
<div [appShortcut]="'ctrl+shift+s'" (shortcutTriggered)="saveDocument()">
Press Ctrl + Shift + S to save.
</div>