CngxFocusTrap
projects/common/a11y/focus/focus-trap.directive.ts
Import#
import { CngxFocusTrap } from '@cngx/common/a11y'
Description#
Traps keyboard focus within the host element using the CDK FocusTrap.
When enabled, Tab and Shift+Tab cycle only within the host element's
focusable children. When autoFocus is true (default), focus moves to
the first tabbable element automatically on activation.
Wraps CDK's FocusTrapFactory with a declarative, Signal-driven API.
The CDK's imperative create() / destroy() / enabled setter lifecycle
is handled internally via effect() and DestroyRef.
Nesting: traps do not coordinate with each other. When traps nest
(dialog over drawer), enable only the innermost one and drive each
enabled from your layering state - two simultaneously enabled traps
fight over Tab. CngxDialogStack already does this for stacked dialogs.
Modal dialog
<div cngxFocusTrap [enabled]="isOpen()" [autoFocus]="true"
tabindex="-1" role="dialog" aria-modal="true"
(keydown.escape)="isOpen.set(false)">
<input placeholder="First input" />
<button (click)="isOpen.set(false)">Close</button>
</div>Drawer / sidebar
<nav cngxFocusTrap [enabled]="drawerOpen()" tabindex="-1">
<a href="/home">Home</a>
<a href="/settings">Settings</a>
</nav>