CngxFocusRestore
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.
When none resolves, focus is left where the browser put it - <body> is
deliberately never a restore target.
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>