skip to content

Dialogs, Snack Bars & Sheets

MatDialog opens a component in an overlay, hands it data through MAT_DIALOG_DATA and returns a MatDialogRef whose afterClosed emits the result. Interviewers ask about focus and close rules.

part ofAngular Material & CDKread it →
on this pageshow

explore

questions

6

In Angular Material, how do you open an archive-project confirmation with `MatDialog` and read the user's choice in the component that opened it?

level: juniorimportance: must knowfreq 58%

answer

  1. inject a service, pass a component
  2. open hands back a reference
  3. buttons bind a close value
  4. one emission, then completion
  5. Escape and backdrop carry no result

basics

~10 s

Inject MatDialog and call open(ArchiveProjectDialog); it returns a MatDialogRef. Buttons close it with [mat-dialog-close]="true" or dialogRef.close(value), and afterClosed() emits that value to the opener, or undefined after Escape or a backdrop click.

solid answer

~40 s

I inject `MatDialog` and call `open(ArchiveProjectDialog)`, which renders the component in a centred overlay with a backdrop and returns a `MatDialogRef<ArchiveProjectDialog, boolean>`. Inside the dialog, the Archive button carries `[mat-dialog-close]="true"`: that directive calls `close()` with its bound value, and it sets the button's `type` to `button` when none is given, so it does not submit a surrounding form. Code can also inject `MatDialogRef` and call `close(value)` itself. The opener subscribes to `afterClosed()`, which emits the result once and completes, so there is nothing to unsubscribe. Escape and a backdrop click close with `undefined`, so I archive only when the result is exactly `true` and treat everything else as Cancel.

code

ts · 22 lines
ts
import {Component} from '@angular/core';
import {MatButton} from '@angular/material/button';
import {
  MatDialogActions,
  MatDialogClose,
  MatDialogContent,
  MatDialogTitle,
} from '@angular/material/dialog';

@Component({
  selector: 'app-archive-project-dialog',
  imports: [MatDialogTitle, MatDialogContent, MatDialogActions, MatDialogClose, MatButton],
  template: `
    <h2 mat-dialog-title>Archive project?</h2>
    <mat-dialog-content>Archived projects leave the board but keep their history.</mat-dialog-content>
    <mat-dialog-actions align="end">
      <button matButton [mat-dialog-close]="false">Cancel</button>
      <button matButton [mat-dialog-close]="true">Archive</button>
    </mat-dialog-actions>
  `,
})
export class ArchiveProjectDialog {}

go deeper

for a junior

Recall the chain: inject MatDialog, call open() with a component, close with mat-dialog-close or close(value), and read the value in afterClosed().

for a middle

Explain why the result can be undefined, why a bound mat-dialog-close differs from a plain attribute, and how the open() type parameters type the result.

for a senior

Show you guard the action on an exact result, know which MatDialogRef observable fires when, and avoid running the action before the user has confirmed.

for a principal

Discuss when a confirmation dialog is the right gate for a destructive action at all, versus an undo affordance, and how a team standardises one dialog pattern.

## What `MatDialog` is `MatDialog` is Angular Material's service for **modal dialogs**: content that opens above the page in an overlay, with a backdrop behind it, and blocks interaction with the page until it closes. You never put a dialog tag in your template. Instead you write an ordinary standalone component for the dialog's content and ask the service to render it. The service is injectable anywhere with `inject(MatDialog)`; no extra provider is needed. The archive-project confirmation in a project tracker is the canonical case: the user picks **Archive** from a project's row, the app asks "Archive project?", and the row only disappears if the user confirms. ## Opening the dialog `open()` takes the component (or a `TemplateRef`) and an optional `MatDialogConfig`: ```ts const ref = this.dialog.open<ArchiveProjectDialog, undefined, boolean>(ArchiveProjectDialog); ``` The three type parameters are the component, the data type and the **result type**. TypeScript cannot infer the result type from anything, so naming it is how `afterClosed()` becomes `Observable<boolean | undefined>` instead of `Observable<any>`. What comes back is a **`MatDialogRef`**, a handle on that one open dialog. The same instance is injectable inside the dialog component, so both sides talk to the same object. The second argument, a `MatDialogConfig`, is optional. Common fields are `width` and `maxWidth`, `data` for passing values in, `disableClose` to ignore Escape and backdrop clicks, and `ariaLabel` when the dialog has no title. Anything you omit keeps its default: a backdrop is shown (`hasBackdrop: true`), focus moves to the first tabbable element (`autoFocus: 'first-tabbable'`), and focus returns to the opener on close (`restoreFocus: true`). App-wide defaults come from the `MAT_DIALOG_DEFAULT_OPTIONS` token. ## Three ways the dialog closes 1. **A close button.** `mat-dialog-close` is an attribute directive. Bound, as in `[mat-dialog-close]="true"`, it closes the dialog with that value. Written as a plain attribute, `mat-dialog-close="true"`, it passes the *string* `"true"`; a bare `mat-dialog-close` passes the attribute's empty string. The directive also sets `type="button"` when the button has no `type`, so a close button inside a form does not submit it. 2. **Code.** The dialog component injects `MatDialogRef` and calls `close(result)`, useful when the result must be computed first. 3. **Dismissal.** Escape and a click on the backdrop close the dialog with **`undefined`**, unless `disableClose` is set in the config. Because dismissal and a bare close button do not produce `true`, the opener should test for the exact value it expects. ## Reading the result `MatDialogRef` exposes several observables. All of them complete when the dialog closes, which is why a one-off subscription to them needs no cleanup. | Member | Emits | |---|---| | `afterOpened()` | once the open animation has finished | | `beforeClosed()` | the result, when closing starts | | `afterClosed()` | the result, after the exit animation, when the overlay is gone | | `backdropClick()` | each click on the backdrop | | `keydownEvents()` | each key pressed while the dialog is open | `afterClosed()` is the one to use for "what did the user choose": by the time it fires, the dialog is gone and the page is interactive again. ## Building the dialog component A standalone dialog imports the pieces it uses: - `MatDialogTitle` (`mat-dialog-title` on a heading; the dialog is labelled by it automatically), - `MatDialogContent` (`<mat-dialog-content>`, the scrollable body), - `MatDialogActions` (`<mat-dialog-actions>`, the button row, with `align="end"` or `align="center"`), - `MatDialogClose` (the `mat-dialog-close` directive), - `MatDialogModule`, if you prefer one import that bundles them. On open, focus moves to the first tabbable element inside the dialog and stays trapped there until it closes, after which it returns to the element that had it before. Those defaults can be changed in the config. ## Mistakes interviewers listen for - Expecting `afterClosed()` to emit `false` on Escape. It emits `undefined`. - Writing `mat-dialog-close="true"` and then comparing the result with `=== true`. The value is a string. - Unsubscribing from `afterClosed()` defensively. It is harmless, but it shows the candidate does not know the observable completes. - Archiving optimistically before the dialog answers. The point of the confirmation is that the action waits for it. - Looking for a returned Promise. `open()` returns a `MatDialogRef`, and the result arrives through an observable. Opening a dialog and reading its result is the screening question for this part of Angular Material. Data passing, focus rules and close guards build on it.

  • Why does a subscription to afterClosed() not need an unsubscribe?
    Every observable on `MatDialogRef` completes when the dialog closes. `afterClosed()` emits the result once and then completes, so the subscription ends on its own. Leaving it open is no leak, and wrapping it in `takeUntilDestroyed()` only matters if the opener might be destroyed while the dialog is still open and you do not want the callback to run then.
  • Can you open a MatDialog from an ng-template instead of a component, and do close buttons still work?
    Yes. `open()` also accepts a `TemplateRef`. The template reads the config's `data` through `let-data`, and `mat-dialog-close` still works: because an embedded view cannot be given the dialog's injector, the directive finds its dialog by looking up the closest open dialog in the DOM instead of injecting `MatDialogRef`.
  • When would you use beforeClosed() rather than afterClosed()?
    `beforeClosed()` emits the same result when closing starts, before the exit animation runs and the overlay is removed. It suits work that should start immediately, such as kicking off the archive request or updating a status line. `afterClosed()` fires once the dialog is fully gone, which is the safer moment to move focus or open another overlay.

  • afterClosed() emits false when the user presses Escape.
  • You must unsubscribe from afterClosed() or the dialog leaks.
  • MatDialog.open() returns a Promise that resolves with the result.
  • mat-dialog-close="true" hands the boolean true to the opener.
  • The opener must poll getState() to find out when the dialog has closed.
open as a page

With Angular Material's `MatDialog`, how does an edit-task dialog receive its task through `MAT_DIALOG_DATA` and return the edited task as a typed result?

level: middleimportance: must knowfreq 50%

basics

~20 s

Pass the task as the data option of open(); the dialog reads it with inject(MAT_DIALOG_DATA). It is the same object, not a copy, so edit a copy and return a new task through a MatDialogRef typed with the result.

open as a page

In Angular Material, how do you build a "Project archived" snack bar with an Undo action using `MatSnackBar`, and when should the archive commit?

level: middleimportance: should knowfreq 42%

basics

~10 s

Call snackBar.open('Project archived', 'Undo', config) and keep the MatSnackBarRef. onAction() fires when Undo is pressed; afterDismissed() reports dismissedByAction, so commit the archive when the snack bar goes away without the action.

open as a page

In Angular Material 22, how do `disableClose`, `closePredicate` and `closeOnNavigation` decide when an edit-task `MatDialog` with unsaved changes may close?

level: seniorimportance: should knowfreq 30%

basics

~20 s

disableClose blocks only Escape and backdrop clicks; closePredicate is asked on every close() and can refuse it; closeOnNavigation closes on back/forward by default, and 'url-change' (22.2.1) closes on any URL change, without asking the predicate.

open as a page

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%

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().

open as a page

In Angular Material 22, how do `MatBottomSheet` and the CDK's `Dialog` differ from `MatDialog`, and when would you reach for each?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

All three open content in a CDK overlay. MatBottomSheet is a phone-first panel at the screen bottom with dismiss() and afterDismissed(), one at a time; the CDK Dialog is the unstyled engine with DialogRef.closed, for dialogs you style yourself.

open as a page