ServiceOptional

WrHotkey

Register keyboard shortcuts like mod+k, where mod is ⌘ on macOS and Ctrl elsewhere.

Installation

Import the class. This entry point has no stylesheet.

import { WrHotkey } from 'ngwr/hotkey';

Usage

Unbind the handle bind() returns on destroy, or use [wrHotkey], which unbinds itself.

private readonly hotkeys = inject(WrHotkey);

constructor() {
  const handle = this.hotkeys.bind('mod+k', () => this.openPalette());
  inject(DestroyRef).onDestroy(() => handle.unbind());
}
<button [wrHotkey]="'mod+k'" (wrHotkeyMatch)="openPalette()">Search</button>
Press ⌘/ (or Ctrl/) anywhere on this page.

API

NameDescriptionTypeDefault
bind(spec, handler, options?)Register a binding. Returns { unbind }.(spec, handler, options?) => WrHotkeyHandle—
[wrHotkey]Directive form: binds on init, re-binds on input change, unbinds on destroy.WrHotkeySpec—
spec format'+'-separated tokens. mod = Cmd on macOS, Ctrl elsewhere.string—
WrHotkeyOptionsThe third argument of bind().interface—
elementListen on this element instead of document. It must hold focus, so add tabindex="0".HTMLElementdocument
preventDefaultCall event.preventDefault() on a match.booleantrue
allowInInputFire while an input, a textarea or a contenteditable has focus.booleanfalse
priorityHigher runs first; a handler calling event.preventDefault() stops the lower ones.number0

[wrHotkey] inputs

Global unless scoped limits it to the host element.

NameDescriptionTypeDefault
wrHotkeyrequiredThe chord to listen for — 'mod+k', 'shift+?', or the full spec object. mod resolves to ⌘ on macOS and Ctrl everywhere else.WrHotkeySpec—
scopedScope the binding to the host element instead of document.booleanfalse
allowInInputFire even when an input / textarea has focus.booleanfalse
preventDefaultSuppress the default action when the binding fires.booleantrue
(wrHotkeyMatch)Emits the original KeyboardEvent on match.KeyboardEvent—

Dependencies

See also