TanStack Hotkeys in Angular
Before starting, load the @tanstack/hotkeys#hotkeys-core skill (npx @tanstack/intent@latest load @tanstack/hotkeys#hotkeys-core).
import { Component, ElementRef, signal, viewChild } from '@angular/core'
import { injectHotkey } from '@tanstack/angular-hotkeys'
@Component({
selector: 'app-panel',
template: `<div #panel tabindex="0" (input)="isDirty.set(true)">Panel</div>`,
})
export class PanelComponent {
readonly isDirty = signal(false)
private readonly panel = viewChild<ElementRef<HTMLDivElement>>('panel')
constructor() {
injectHotkey(
'Mod+S',
() => this.save(),
() => ({ enabled: this.isDirty() }),
)
// A viewChild signal target registers once the element renders.
injectHotkey('Escape', () => this.close(), { target: this.panel })
}
save() {}
close() {}
}
API
| API |
What it's for |
injectHotkey(hotkey, callback, options?) |
Register one chord, sequence, or app hotkey for the component's or service's lifetime; options can be a function that reads signals. |
injectHotkeys(definitions, commonOptions?) |
Register several hotkeys, or a function returning a list built from data, in one call. |
provideHotkeys(options) |
Set default options, a scope (exclusive for dialogs), enabled, and app hotkeys in the app config or a component's providers. |
injectHotkeysContext() |
Read the nearest provided defaults and enabled state. Activates that provider's scope. |
injectDefaultHotkeysOptions() |
Read the default options merged from every provider above. |
injectFormatForDisplay() |
Get formatForDisplay with the provider's platform filled in, for labels in server-rendered apps. Call it in an injection context. |
injectAppHotkeys() |
Get a signal of the declared app hotkeys with the user's custom hotkeys applied. |
injectAppHotkeyList() |
Get a signal listing every app hotkey with its status, for a cheat sheet or settings screen. |
injectCustomHotkeys() |
Read, change, and reset the user's custom hotkeys, and check a new one for conflicts. |
injectHotkeyRecorder(options) |
Record a chord or sequence the user presses, for a settings screen. |
injectHotkeyRegistrations() |
Get a signal listing every registered hotkey with its options, meta, and status (whether it's enabled and in an active scope). |
injectHotkeyScopesState() |
Get a signal of the active scopes and the exclusive scope that owns the keyboard. |
injectHotkeyHint(hotkey, options?) |
Get a signal of whether held modifiers should reveal a shortcut's hint. False unless a registration of the hotkey can fire: enabled, in an active scope, and with focus inside its element target. |
injectKeyHold(key) |
Get a signal of whether one key is held. Letters match in any case; other names, such as Shift, are case-sensitive. |
injectHeldKeys() |
Get a signal of every key that's held right now. |
injectHeldKeyCodes() |
Get a signal mapping each held key to its physical event.code. |
The package also re-exports @tanstack/hotkeys, such as formatForDisplay, matchesKeyboardEvent, and defineAppHotkeys.
No provider is required. Call the inject functions in a constructor or field initializer.
A dialog that owns the keyboard
import { Component, InjectionToken, inject, output } from '@angular/core'
import { injectHotkey, provideHotkeys } from '@tanstack/angular-hotkeys'
let nextDialogId = 0
const DIALOG_SCOPE = new InjectionToken<string>('DIALOG_SCOPE')
@Component({
selector: 'app-dialog',
providers: [
{ provide: DIALOG_SCOPE, useFactory: () => `dialog-${++nextDialogId}` },
provideHotkeys({ scope: () => inject(DIALOG_SCOPE), exclusive: true }),
],
template: `<div role="dialog"><ng-content /></div>`,
})
export class DialogComponent {
readonly closed = output()
constructor() {
injectHotkey('Escape', () => this.closed.emit())
}
}
A component's providers apply to the component itself, so it can register its own scoped hotkeys. A fixed scope: 'dialog' would give every open dialog the same scope; the per-instance token gives each its own.
Pitfalls
- Pass options as a function.
{ enabled: this.isDirty() } is read once, in the constructor. Use () => ({ ... }).
- Pass the
viewChild signal as target, not its value. { target: this.panel() } reads the signal once in the constructor, where it is undefined, so the hotkey waits and never registers. { target: this.panel } waits for the element and follows it. Reading the value inside an options function, such as () => ({ target: this.panel()?.nativeElement }), also works.
- An exclusive provider with no hotkeys never activates. Angular creates providers lazily. Call
injectHotkeysContext() in the component's constructor to activate the scope.
- Put scoped providers in a component's
providers, not Route.providers. The router keeps a route's injector after navigation, so its scope stays active on the next page, and an exclusive one suspends every other hotkey. Provide the scope on the page component. On Angular 22.2 or later, withAutoCleanupInjectors() in provideRouter also works, as long as the route reuse strategy's shouldDestroyInjector returns true (the default strategy does) and it reports stored pages through retrieveStoredRouteHandles(). A stored page keeps its injector and its scope, so disable that scope with enabled on the outlet's (detach) and restore it on (attach).
- Replace
@HostListener('document:keydown') and (keydown.control.s) bindings with injectHotkey.
- Hotkeys in a service outside any component can't update a view through plain fields. Callbacks registered in a component or directive mark that component for check, so field changes render in OnPush and zoneless apps. A root or route-level service has no component to mark; store the state its hotkeys change in signals.
- Register runtime lists in the constructor.
injectHotkey throws outside an injection context, such as in ngOnInit. For hotkeys from data, use injectHotkeys(() => this.items().map(...)).
- Call the inject functions directly. A shortcut service or
injectShortcut(keys: string) wrapper has to cast strings to hotkeys, which turns off type checking and drops sequences, signal options, and app hotkeys.
- Server-rendered labels need the user's platform. On the server,
formatForDisplay can't see the user's OS, so it renders Linux labels that differ after hydration for Mac and Windows users. Pass provideHotkeys({ defaultOptions: () => ({ platform: detectPlatform(inject(REQUEST)?.headers.get('user-agent')) }) }), and format labels with format = injectFormatForDisplay() as a field, then format(hotkey) in the template. Keep plain formatForDisplay for labels that render only in the browser, when no provider sets platform.
When declaring app hotkeys, building a cheat sheet, or letting users rebind shortcuts, load @tanstack/hotkeys#app-hotkeys and read app hotkeys in Angular.
API discovery and docs
Signatures: node_modules/@tanstack/angular-hotkeys/dist/*.d.ts. Guides: https://tanstack.com/hotkeys/latest/docs/framework/angular/guides/<page>.md, such as hotkeys, provide-hotkeys-and-scopes, or app-hotkeys. Devtools (Angular 21+): hotkeysDevtoolsPlugin() from @tanstack/angular-hotkeys-devtools with provideTanStackDevtools.
1---2name: tanstack-angular-hotkeys3description: "Use when adding or fixing keyboard shortcuts in an Angular app with @tanstack/angular-hotkeys: injectHotkey and injectHotkeys in an injection context, signal-driven options, viewChild targets, provideHotkeys defaults and component scopes, app hotkey injectors, recorders, held-key and hint injectors, or replacing @HostListener keydown handlers."4license: "MIT"5metadata:6 source: https://skillmd.com/skills/lukasa1993/tanstack-angular-hotkeys7 internal: true8 tanstack-framework: "angular"9 tanstack-library: "@tanstack/angular-hotkeys"10 tanstack-library-version: "0.15.0"11 tanstack-package: "@tanstack/angular-hotkeys"12 tanstack-package-version: "0.22.1"13 tanstack-purpose: "Angular bindings for TanStack Hotkeys: inject functions, signal-driven options, provideHotkeys scopes, and the Angular-specific mistakes to avoid."14 tanstack-requires: "[\"tanstack-hotkeys-core\"]"15 tanstack-source-skill: "angular-hotkeys"16 tanstack-sources: "[\"src/injectHotkey.ts\",\"src/injectHotkeys.ts\",\"src/hotkeys-provider.ts\",\"src/injectAppHotkeys.ts\",\"src/injectHotkeyRecorder.ts\",\"TanStack/hotkeys:docs/framework/angular/quick-start.md\",\"TanStack/hotkeys:docs/framework/angular/guides/provide-hotkeys-and-scopes.md\"]"17 tanstack-type: "framework"18---1920# TanStack Hotkeys in Angular2122Before starting, load the `@tanstack/hotkeys#hotkeys-core` skill (`npx @tanstack/intent@latest load @tanstack/hotkeys#hotkeys-core`).2324```ts25import { Component, ElementRef, signal, viewChild } from '@angular/core'26import { injectHotkey } from '@tanstack/angular-hotkeys'2728@Component({29 selector: 'app-panel',30 template: `<div #panel tabindex="0" (input)="isDirty.set(true)">Panel</div>`,31})32export class PanelComponent {33 readonly isDirty = signal(false)34 private readonly panel = viewChild<ElementRef<HTMLDivElement>>('panel')3536 constructor() {37 injectHotkey(38 'Mod+S',39 () => this.save(),40 () => ({ enabled: this.isDirty() }),41 )42 // A viewChild signal target registers once the element renders.43 injectHotkey('Escape', () => this.close(), { target: this.panel })44 }4546 save() {}47 close() {}48}49```5051## API5253| API | What it's for |54| -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |55| `injectHotkey(hotkey, callback, options?)` | Register one chord, sequence, or app hotkey for the component's or service's lifetime; options can be a function that reads signals. |56| `injectHotkeys(definitions, commonOptions?)` | Register several hotkeys, or a function returning a list built from data, in one call. |57| `provideHotkeys(options)` | Set default options, a scope (`exclusive` for dialogs), `enabled`, and app hotkeys in the app config or a component's `providers`. |58| `injectHotkeysContext()` | Read the nearest provided defaults and enabled state. Activates that provider's scope. |59| `injectDefaultHotkeysOptions()` | Read the default options merged from every provider above. |60| `injectFormatForDisplay()` | Get `formatForDisplay` with the provider's `platform` filled in, for labels in server-rendered apps. Call it in an injection context. |61| `injectAppHotkeys()` | Get a signal of the declared app hotkeys with the user's custom hotkeys applied. |62| `injectAppHotkeyList()` | Get a signal listing every app hotkey with its status, for a cheat sheet or settings screen. |63| `injectCustomHotkeys()` | Read, change, and reset the user's custom hotkeys, and check a new one for conflicts. |64| `injectHotkeyRecorder(options)` | Record a chord or sequence the user presses, for a settings screen. |65| `injectHotkeyRegistrations()` | Get a signal listing every registered hotkey with its options, `meta`, and `status` (whether it's enabled and in an active scope). |66| `injectHotkeyScopesState()` | Get a signal of the active scopes and the exclusive scope that owns the keyboard. |67| `injectHotkeyHint(hotkey, options?)` | Get a signal of whether held modifiers should reveal a shortcut's hint. False unless a registration of the hotkey can fire: enabled, in an active scope, and with focus inside its element target. |68| `injectKeyHold(key)` | Get a signal of whether one key is held. Letters match in any case; other names, such as `Shift`, are case-sensitive. |69| `injectHeldKeys()` | Get a signal of every key that's held right now. |70| `injectHeldKeyCodes()` | Get a signal mapping each held key to its physical `event.code`. |7172The package also re-exports `@tanstack/hotkeys`, such as `formatForDisplay`, `matchesKeyboardEvent`, and `defineAppHotkeys`.7374No provider is required. Call the inject functions in a constructor or field initializer.7576## A dialog that owns the keyboard7778```ts79import { Component, InjectionToken, inject, output } from '@angular/core'80import { injectHotkey, provideHotkeys } from '@tanstack/angular-hotkeys'8182let nextDialogId = 083const DIALOG_SCOPE = new InjectionToken<string>('DIALOG_SCOPE')8485@Component({86 selector: 'app-dialog',87 providers: [88 { provide: DIALOG_SCOPE, useFactory: () => `dialog-${++nextDialogId}` },89 provideHotkeys({ scope: () => inject(DIALOG_SCOPE), exclusive: true }),90 ],91 template: `<div role="dialog"><ng-content /></div>`,92})93export class DialogComponent {94 readonly closed = output()9596 constructor() {97 injectHotkey('Escape', () => this.closed.emit())98 }99}100```101102A component's `providers` apply to the component itself, so it can register its own scoped hotkeys. A fixed `scope: 'dialog'` would give every open dialog the same scope; the per-instance token gives each its own.103104## Pitfalls105106- **Pass options as a function.** `{ enabled: this.isDirty() }` is read once, in the constructor. Use `() => ({ ... })`.107- **Pass the `viewChild` signal as `target`, not its value.** `{ target: this.panel() }` reads the signal once in the constructor, where it is `undefined`, so the hotkey waits and never registers. `{ target: this.panel }` waits for the element and follows it. Reading the value inside an options function, such as `() => ({ target: this.panel()?.nativeElement })`, also works.108- **An exclusive provider with no hotkeys never activates.** Angular creates providers lazily. Call `injectHotkeysContext()` in the component's constructor to activate the scope.109- **Put scoped providers in a component's `providers`, not `Route.providers`.** The router keeps a route's injector after navigation, so its scope stays active on the next page, and an exclusive one suspends every other hotkey. Provide the scope on the page component. On Angular 22.2 or later, `withAutoCleanupInjectors()` in `provideRouter` also works, as long as the route reuse strategy's `shouldDestroyInjector` returns `true` (the default strategy does) and it reports stored pages through `retrieveStoredRouteHandles()`. A stored page keeps its injector and its scope, so disable that scope with `enabled` on the outlet's `(detach)` and restore it on `(attach)`.110- **Replace `@HostListener('document:keydown')` and `(keydown.control.s)` bindings with `injectHotkey`.**111- **Hotkeys in a service outside any component can't update a view through plain fields.** Callbacks registered in a component or directive mark that component for check, so field changes render in OnPush and zoneless apps. A root or route-level service has no component to mark; store the state its hotkeys change in signals.112- **Register runtime lists in the constructor.** `injectHotkey` throws outside an injection context, such as in `ngOnInit`. For hotkeys from data, use `injectHotkeys(() => this.items().map(...))`.113- **Call the inject functions directly.** A shortcut service or `injectShortcut(keys: string)` wrapper has to cast strings to hotkeys, which turns off type checking and drops sequences, signal options, and app hotkeys.114- **Server-rendered labels need the user's platform.** On the server, `formatForDisplay` can't see the user's OS, so it renders Linux labels that differ after hydration for Mac and Windows users. Pass `provideHotkeys({ defaultOptions: () => ({ platform: detectPlatform(inject(REQUEST)?.headers.get('user-agent')) }) })`, and format labels with `format = injectFormatForDisplay()` as a field, then `format(hotkey)` in the template. Keep plain `formatForDisplay` for labels that render only in the browser, when no provider sets `platform`.115116When declaring app hotkeys, building a cheat sheet, or letting users rebind shortcuts, load `@tanstack/hotkeys#app-hotkeys` and read [app hotkeys in Angular](./references/app-hotkeys.md).117118## API discovery and docs119120Signatures: `node_modules/@tanstack/angular-hotkeys/dist/*.d.ts`. Guides: `https://tanstack.com/hotkeys/latest/docs/framework/angular/guides/<page>.md`, such as `hotkeys`, `provide-hotkeys-and-scopes`, or `app-hotkeys`. Devtools (Angular 21+): `hotkeysDevtoolsPlugin()` from `@tanstack/angular-hotkeys-devtools` with `provideTanStackDevtools`.