Focus Trap
A directive that keeps focus inside an element while it is shown — the dialog, alert dialog, drawer, sheet and popover use it.
Usage
import { Component, ViewEncapsulation, signal } from '@angular/core';import { ScButton, ScFocusTrap } from '@semantic-components/ui';
@Component({ selector: 'app-focus-trap-usage-demo', imports: [ScButton, ScFocusTrap], template: ` <button scButton variant="outline" (click)="open.set(true)">Open</button> @if (open()) { <div scFocusTrap class="flex gap-2"> <button scButton>Stay</button> <button scButton (click)="open.set(false)">Close</button> </div> } `, host: { class: 'flex w-full justify-center gap-2' }, encapsulation: ViewEncapsulation.None,})export class FocusTrapUsageDemo { private readonly open = signal(false);}Anatomy
One directive on the element shown — a dialog, a panel: focus moves in, Tab stays inside, and focus goes back where it came from when it goes away.
import { ScFocusTrap } from '@semantic-components/ui';@if (open()) { <div scFocusTrap>…</div>}How It Works
- Once rendered, focuses the element's first focusable child (or the one marked
cdkFocusInitial). - Tab and Shift + Tab wrap round inside it.
- When it goes away, focus goes back to where it was before — only if it is still inside, or lost to the page. Focus that moved on (into a dialog opened from a popover, say) is left where it is, as the CDK's Dialog does;
cdkTrapFocuswould take it back.
Why not cdkTrapFocus
It is the CDK's focus trap underneath (FocusTrapFactory), with two changes:
- Giving focus back.
cdkTrapFocus(withcdkTrapFocusAutoCapture) always focuses the element that had focus before. A popover that opens a dialog, then closes, would pull focus out of the dialog, back to its own trigger. This one gives it back only when it is still inside, or lost to the page — as the CDK's Dialog does. - Not trapped, still moving in.
[scFocusTrap]="false"moves focus in and back, but lets Tab leave — Base UI's Popover, not modal by default. With the CDK, its restore would still be unconditional. - On by default. Focus moves in without an extra input; with the CDK each overlay must add
cdkTrapFocusAutoCapture.
The Dialog, Alert Dialog, Sheet, Drawer and Popover use it.
Examples
A panel
import { Component, ViewEncapsulation, signal } from '@angular/core';import { ScButton, ScField, ScFocusTrap, ScFrame, ScInput, ScLabel,} from '@semantic-components/ui';API reference
A behaviour only, on any element.
| Part | Selector | Description |
|---|---|---|
ScFocusTrap | [scFocusTrap] | Focuses the first focusable element once rendered (or the one marked cdkFocusInitial); Tab and Shift+Tab wrap inside. [scFocusTrap]="false": focus still moves in and comes back, but Tab may leave (a non-modal popover). On the way out, focus goes back only if it was still inside, or lost to the page. |