Skip to main content
cngx-src documentation

CngxFocusTrap

DirectivePrimaryv0.1.0WCAG AA

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.

<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>

https://cngxjs.github.io/cngx/examples/#/common/a11y/focus-trap/modal-dialog https://cngxjs.github.io/cngx/examples/#/common/a11y/focus-trap/slide-out-drawer

Metadata#

Index#

Inputs#

autoFocus#boolean
input()

Whether to auto-focus the first tabbable element when the trap activates.

default true
enabled#boolean
input()

Whether the focus trap is active. When false, Tab navigates normally.

default false

Methods#

focusFirst#void

Programmatically focus the first tabbable element within the trap.

focusLast#void

Programmatically focus the last tabbable element within the trap.