Skip to main content
cngx-src documentation

CngxFocusRestore

DirectivePrimaryv0.1.0WCAG AA

projects/common/a11y/focus/focus-restore.directive.ts

Import#

import { CngxFocusRestore } from '@cngx/common/a11y'

Description#

Stores the previously focused element and restores focus on destroy.

Prevents focus from falling to <body> when dynamic content is removed (dialogs closing, panels collapsing, tabs switching). The directive captures document.activeElement at initialization time and restores it when the host element is destroyed.

Fallback chain: stored element → provided fallback → nearest focusable ancestor → body.

Panel that restores focus on close

@if (panelOpen()) {
  <div cngxFocusRestore>
    Panel content…
    <button (click)="panelOpen.set(false)">Close</button>
  </div>
}

With explicit fallback

<div cngxFocusRestore [focusRestoreFallback]="fallbackBtn">
  Dynamic content…
</div>
<button #fallbackBtn>Fallback target</button>

https://cngxjs.github.io/cngx/examples/#/common/a11y/focus-restore/inline-details https://cngxjs.github.io/cngx/examples/#/common/a11y/focus-restore/panel-with-automatic-restore

Metadata#

Index#

Inputs#

fallback#HTMLElement | null
input()

Explicit fallback element if the stored element is no longer in the DOM.

default null
restoreOnDestroy#boolean
input()

Whether to restore focus when the host element is destroyed.

default true

Methods#

capture#void

Manually store the current focus target for later restoration.

restore#void

Manually restore focus to the stored element.