skip to content

Why does the Angular CDK's `cdkTrapFocus` on a custom filter drawer neither move focus in on open nor return it on close?

level: middleimportance: must knowfreq 34%

answer

  1. Tab wrapping, not focus capture
  2. hidden anchors before and after
  3. an opt-in input for capture
  4. restore happens on destroy
  5. cdkFocusInitial needs autoCapture

basics

~20 s

cdkTrapFocus only keeps Tab and Shift+Tab cycling inside its element and never captures focus by default. Add cdkTrapFocusAutoCapture: it focuses the cdkFocusInitial or first tabbable element on init and refocuses the previous element when the directive is destroyed.

solid answer

~40 s

`cdkTrapFocus` inserts two hidden, tabbable anchor elements before and after its host; when Tab or Shift+Tab lands on one, focus wraps to the first or last tabbable element inside. That is all it does by default. Moving focus in and handing it back is the opt-in `cdkTrapFocusAutoCapture` input: on initialisation it remembers `document.activeElement` and focuses the element marked `cdkFocusInitial` (or the first tabbable one), and in `ngOnDestroy` it refocuses the remembered element. So the drawer must actually be destroyed, typically rendered inside `@if`, for focus to return; a drawer hidden with a CSS class never is. `cdkFocusInitial` is ignored without autoCapture, and pointer clicks outside the drawer are not blocked at all.

code

ts · 19 lines
ts
import {Component, signal} from '@angular/core';
import {CdkTrapFocus} from '@angular/cdk/a11y';

@Component({
  selector: 'app-filter-drawer-host',
  imports: [CdkTrapFocus],
  template: `
    <button type="button" (click)="open.set(true)">Filters</button>
    @if (open()) {
      <aside role="dialog" aria-label="Filters" cdkTrapFocus cdkTrapFocusAutoCapture>
        <input cdkFocusInitial placeholder="Search filters" />
        <button type="button" (click)="open.set(false)">Apply</button>
      </aside>
    }
  `,
})
export class FilterDrawerHost {
  open = signal(false);
}

go deeper

for a junior

Remember the pair: cdkTrapFocus keeps Tab inside the panel, and cdkTrapFocusAutoCapture is what moves focus in on open and back out when the panel is destroyed.

for a middle

Explain the anchor mechanism, why cdkFocusInitial is ignored without autoCapture, and why the drawer must be removed with @if rather than hidden for focus to return.

for a senior

Show you know where the directive stops: no pointer blocking, DOM-order assumptions, kept-in-DOM drawers needing manual restore, and the v22 config-object form of ConfigurableFocusTrapFactory.create.

for a principal

Frame when a team should rely on Material's own dialog or drawer traps versus owning a trap in custom markup, and what each choice leaves the team to test.

## What `cdkTrapFocus` actually does The Angular CDK's `@angular/cdk/a11y` package ships a **focus trap**: a utility that keeps keyboard focus inside one region, such as a modal panel. You use it through the `CdkTrapFocus` directive, selector `[cdkTrapFocus]`, imported into a standalone component's `imports`. The mechanism is deliberately simple: - When the directive initialises, it creates a `FocusTrap` and inserts two **anchor** `div`s as siblings of the host, one immediately before and one immediately after it. - Each anchor carries `tabindex="0"`, `aria-hidden="true"` and the `cdk-visually-hidden` class, so it is reachable by Tab but invisible and silent. - When Tab moves focus onto the end anchor, a listener sends focus to the **first** tabbable element inside the region; Shift+Tab onto the start anchor sends it to the **last** one. - `cdkFocusRegionStart` and `cdkFocusRegionEnd` attributes can narrow the region whose ends are used. Nothing in that list moves focus *into* the region or hands it *back*. That is why a drawer that opens with only `cdkTrapFocus` leaves focus on the button that opened it: the trap is armed, but the user is still outside it. ## What it does and does not do | Behaviour | `cdkTrapFocus` alone | with `cdkTrapFocusAutoCapture` | |---|---|---| | Tab and Shift+Tab wrap inside the region | yes | yes | | Focus moves into the region on init | no | yes, to `cdkFocusInitial` or the first tabbable element | | Focus returns to the previous element | no | yes, in the directive's `ngOnDestroy` | | Mouse clicks outside are prevented | no | no | Two details trip people up: 1. **`cdkFocusInitial` does nothing on its own.** The trap reads that marker only when something asks it to focus the initial element, and the directive does that only when autoCapture is on. 2. **Restoring focus is tied to destruction.** The directive stores the previously focused element when it captures focus and refocuses it in `ngOnDestroy`. A drawer kept in the DOM and hidden with a class is never destroyed, so nothing is restored. ## Wiring it on a slide-in filter drawer ```html <button type="button" (click)="open.set(true)">Filters</button> @if (open()) { <aside role="dialog" aria-label="Filters" cdkTrapFocus cdkTrapFocusAutoCapture> <input cdkFocusInitial placeholder="Search filters" /> <button type="button" (click)="open.set(false)">Apply</button> </aside> } ``` When `open` becomes true the block renders, the directive remembers the Filters button and focuses the search input after the view is stable. When Apply sets `open` to false, `@if` destroys the drawer, the directive's `ngOnDestroy` runs, and focus goes back to the Filters button. If the drawer must stay in the DOM, for example to keep a slide-out animation, bind the enabled state instead: `[cdkTrapFocus]="open()"` disables the anchors while it is closed. Disabling does **not** restore focus, and re-enabling does not capture it again, because autoCapture runs on initialisation (or when the autoCapture input itself turns on). You then move focus in and return it yourself, for instance by calling `focus()` on the trigger when the drawer closes. ## Limits worth knowing - The trap assumes **tab order equals DOM order**. A positive `tabindex`, flex `order` or shadow roots can make the first and last tabbable elements differ from what the user sees. - It only intercepts Tab. A pointer click on a link behind the drawer moves focus out; making the page behind non-interactive is a separate concern (a backdrop, or the `inert` attribute). - Since 22.1.2, when the region contains nothing tabbable, wrapping falls back to the trap's root element, provided that root is itself focusable, for example through `tabindex="-1"`. ## Building a trap in code For a component that needs a trap without the directive, inject a factory: - `FocusTrapFactory.create(element)` returns a plain `FocusTrap`; call `focusInitialElementWhenReady()` to move focus in and `destroy()` to remove the anchors. Restoring focus is then your job. - `ConfigurableFocusTrapFactory.create(element, config)` returns a `ConfigurableFocusTrap`. In CDK 22 the second argument is a config object such as `{defer: true}`, replacing the boolean of earlier majors, and the trap constructors now require an `injector`. - A `ConfigurableFocusTrap` registers with a stack so only the most recently enabled trap is active, and its default inert strategy listens for `focus` on the document and pulls focus back when it lands outside the region, ignoring CDK overlay panes. A custom strategy is supplied through `FOCUS_TRAP_INERT_STRATEGY`. Angular Material's dialog and drawer create their own traps internally, so you reach for `cdkTrapFocus` when the panel is your own markup, like this filter drawer.

  • How do you create the same trap from code in CDK 22, and what changed from earlier majors?
    Inject `ConfigurableFocusTrapFactory` (or `FocusTrapFactory`) and call `create(element, {defer: true})`, then `attachAnchors()` and `focusInitialElementWhenReady()`; call `destroy()` when the panel closes. Since 22.0.0 the second argument of `ConfigurableFocusTrapFactory.create` is a config object instead of a boolean, and the `FocusTrap` and `ConfigurableFocusTrap` constructors require an `injector`. Returning focus is your responsibility in this form.
  • What does a ConfigurableFocusTrap add over the trap that cdkTrapFocus creates?
    It registers with a focus-trap stack, so opening a second trap disables the first and destroying it re-enables the previous one. Its default inert strategy also listens for `focus` events on the document and moves focus back into the region when it lands outside, while ignoring elements inside CDK overlay panes. You can replace that strategy through the `FOCUS_TRAP_INERT_STRATEGY` token.
  • Why can Tab land on an unexpected element inside a cdkTrapFocus region?
    The trap finds the first and last tabbable elements by walking the DOM, assuming tab order matches DOM order. A positive `tabindex`, CSS flex `order` or content in shadow roots can make the visual or actual tab order differ, so the wrap target is not the element the user expects. Keeping DOM order equal to visual order, or marking the ends with `cdkFocusRegionStart` and `cdkFocusRegionEnd`, fixes it.

  • cdkTrapFocus moves focus into the panel as soon as it renders.
  • cdkTrapFocus stops mouse clicks from moving focus outside the panel.
  • cdkFocusInitial works on its own without cdkTrapFocusAutoCapture.
  • Hiding the drawer with a CSS class is enough for focus to be restored.
  • Setting cdkTrapFocus to false hands focus back to the trigger.
  • ConfigurableFocusTrapFactory.create still takes a boolean defer flag in v22.

Assumes Angular CDK 22; ConfigurableFocusTrapFactory.create takes a config object and the FocusTrap constructors require an injector since 22.0.0.