skip to content

An Angular Material `MatDialog` archive confirmation opened from a row menu focuses the Archive button, and focus vanishes after it closes; which `MatDialogConfig` options fix both?

level: seniorimportance: should knowfreq 34%

answer

  1. default lands on the first tabbable
  2. markup order decides the target
  3. selector, heading or container
  4. restoring to a removed element
  5. a selector or an element instead

basics

~20 s

autoFocus defaults to 'first-tabbable', so the first button in the markup gets focus; aim it at Cancel with a CSS selector. restoreFocus: true targets the menu item, which is gone; pass a selector or element, or refocus in afterClosed().

solid answer

~40 s

`MatDialogConfig.autoFocus` defaults to `'first-tabbable'`, so focus goes to the first tabbable element in the dialog, here the Archive button because it comes first in the markup. Its other values are `'first-heading'`, `'dialog'` (the container itself) or any CSS selector, so `autoFocus: '.keep-project'` lands on Cancel; a `cdkFocusInitial` attribute on Cancel does the same through the focus trap. On close, `restoreFocus` defaults to `true`, meaning the element focused when the dialog opened, which was the menu item, and the menu has since removed it, so focus falls to the body. `restoreFocus` also accepts a CSS selector or an `HTMLElement`, so I point it at the row's menu trigger, or set it to `false` and focus something sensible in `afterClosed()`, because after a confirmed archive the row itself disappears.

code

ts · 29 lines
ts
import {Component, ElementRef, inject, viewChild} from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import {MatMenuModule} from '@angular/material/menu';
import {ArchiveProjectDialog} from './archive-project-dialog';

@Component({
  selector: 'app-project-row-menu',
  imports: [MatMenuModule],
  template: `
    <button #trigger [matMenuTriggerFor]="menu" aria-label="Project actions">...</button>
    <mat-menu #menu><button mat-menu-item (click)="confirmArchive()">Archive</button></mat-menu>
  `,
})
export class ProjectRowMenu {
  private dialog = inject(MatDialog);
  private trigger = viewChild.required<ElementRef<HTMLElement>>('trigger');

  confirmArchive() {
    const ref = this.dialog.open<ArchiveProjectDialog, undefined, boolean>(ArchiveProjectDialog, {
      role: 'alertdialog',
      autoFocus: '.keep-project', // the Cancel button, not Archive
      restoreFocus: false, // the menu item is gone; decide below
    });
    ref.afterClosed().subscribe(archived => {
      if (archived !== true) this.trigger().nativeElement.focus();
      // on Archive the row leaves the board; the list moves focus to a neighbour
    });
  }
}

go deeper

for a junior

Recall that a MatDialog moves focus into itself on open and back to the opener on close, and that autoFocus and restoreFocus control those two moves.

for a middle

Explain the 'first-tabbable' default and its DOM-order rule, the other autoFocus values, and what restoreFocus: true restores to.

for a senior

Diagnose focus lost after a menu-opened dialog, choose a restore target per outcome, and keep destructive actions out of the initial focus.

for a principal

Set app-wide focus conventions for dialogs through MAT_DIALOG_DEFAULT_OPTIONS, knowing the provided object replaces rather than merges the defaults.

## Two focus moments, two options A `MatDialog` manages focus twice: when it **opens**, it moves focus into the dialog and traps it there; when it **closes**, it tries to put focus back. `MatDialogConfig` has one option for each moment, `autoFocus` and `restoreFocus`, and the same pair exists on `MatBottomSheetConfig` and on the CDK's `DialogConfig`. The trap itself (keeping Tab inside the dialog) is a separate mechanism from the CDK's accessibility package; these two options decide only *where* focus lands. ## Why focus lands on Archive `autoFocus` defaults to **`'first-tabbable'`**. After the dialog renders, Material asks its focus trap for the initial element: an element marked `cdkFocusInitial` if there is one, otherwise the **first tabbable element in DOM order**. If the template is ```html <mat-dialog-actions align="end"> <button matButton [mat-dialog-close]="true">Archive</button> <button matButton [mat-dialog-close]="false">Cancel</button> </mat-dialog-actions> ``` then Archive is first, and a user who presses Enter by reflex archives the project. Visual order and DOM order can also differ: CSS such as `flex-direction: row-reverse` can show Cancel on the left while Archive is still first in the markup, and focus follows the markup. The values `autoFocus` accepts: | Value | Where focus goes | |---|---| | `'first-tabbable'` (default) | the `cdkFocusInitial` element, else the first tabbable element, else the container | | `'first-heading'` | the first `h1`-`h6` or `role="heading"` element | | `'dialog'` | the dialog container, unless focus is already inside the dialog | | any CSS selector | the first element matching it | | `false` | the same as `'dialog'`; the boolean form is the older spelling | For a destructive confirmation the usual fixes are: 1. `autoFocus: '.keep-project'`, a selector for the Cancel button; 2. `autoFocus: 'first-heading'`, so a screen reader starts at the question; 3. a `cdkFocusInitial` attribute on Cancel, keeping the default option; 4. reordering the markup, if the design allows it. The headings case has a detail worth knowing: a heading is not focusable, so Material adds a temporary `tabindex="-1"` and removes it on blur. Material's own guide spells this value `first-header`, but the source type `AutoFocusTarget` is `'first-heading'`; the source wins. ## Why focus vanishes on close `restoreFocus` defaults to **`true`**: focus goes back to the element that had it when the dialog opened. The dialog was opened from a `mat-menu` item, so that element was the **menu item**, and the menu closed and removed it from the DOM. Focus on a detached element goes nowhere, and keyboard and screen-reader users land on the page body, far from where they were. Material's guide calls out exactly this menu case. The options: | `restoreFocus` value | Behaviour | |---|---| | `true` (default) | the element focused before opening | | `false` | no restoration; you move focus yourself | | a CSS selector string | the first matching element in the document | | an `HTMLElement` | that element | There is a second complication: after a **confirmed** archive, the project row, menu trigger included, leaves the board. So the robust pattern is `restoreFocus: false` and a decision in `afterClosed()`: on Cancel, focus the row's menu trigger; on Archive, focus a stable neighbour such as the next row or the list heading. Restoration also only happens when focus is still inside the dialog or on the body at close time; if your code has already moved focus elsewhere, Material leaves it alone. ## Related knobs - **`delayFocusTrap`** (Material only, default `true`) waits for the open animation before trapping focus. - **`role: 'alertdialog'`** suits a confirmation that interrupts the user, and the title is wired as the dialog's label automatically. - **`ariaDescribedBy`** can point at the body text, so a screen reader announces the consequence as well as the question when focus lands on a button. - Defaults for the whole app come from `MAT_DIALOG_DEFAULT_OPTIONS`; note that the provided object **replaces** the built-in defaults rather than merging with them, so spread `new MatDialogConfig()` first. ## What a senior answer shows - Knowing both defaults and that DOM order, not visual prominence, picks the first target. - Knowing restoration fails when the opener element is removed, and that the row may go too. - Choosing a target per outcome rather than one global setting.

  • What does delayFocusTrap change, and why is it on by default in MatDialog?
    With `delayFocusTrap: true`, the default, Material waits for the dialog's open animation to finish before trapping focus and moving it to the `autoFocus` target. Focusing an element while it is still animating in can make the browser scroll or flash the page. The option exists on `MatDialogConfig` only; the CDK's `DialogConfig` has no animation to wait for.
  • Why might restoreFocus: true still do nothing even though the opener button exists?
    Material only restores focus if, at close time, focus is still inside the dialog or on the body. If code in a `beforeClosed()` handler, or another overlay, has already moved focus somewhere else, Material assumes that was deliberate and leaves it. The restore target must also be focusable; a plain `div` without `tabindex` will not take focus.

  • MatDialog focuses the dialog container by default, never a button.
  • The most visually prominent button gets initial focus in a MatDialog.
  • restoreFocus: true always works because Material remembers the opener element safely.
  • restoreFocus only accepts a boolean, so custom targets need a focus trap.
  • autoFocus: 'first-heading' fails because headings cannot receive focus.