skip to content

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%

answer

  1. message, action label, config
  2. one stream for the action button
  3. dismissal reports how it ended
  4. default duration keeps it open
  5. only one on screen at once

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.

solid answer

~40 s

`MatSnackBar.open(message, action, config)` returns a `MatSnackBarRef`. Its `onAction()` emits when the user presses the action button, and `afterDismissed()` emits a `MatSnackBarDismiss` whose `dismissedByAction` says whether that was how it ended. For a deferred archive I hide the project immediately and commit in `afterDismissed()` when `dismissedByAction` is false; for an optimistic one I archive at once and reverse it in `onAction()`. Two defaults matter: `duration` is `0`, so without a value the snack bar stays until dismissed, and only one snack bar shows at a time, so archiving a second project dismisses the first, which then commits. It announces through a `polite` live region and never takes focus, so Undo must also exist somewhere reachable without it.

code

ts · 24 lines
ts
import {inject, Injectable} from '@angular/core';
import {MatSnackBar} from '@angular/material/snack-bar';
import {ProjectStore} from './project-store';

@Injectable({providedIn: 'root'})
export class ArchiveWithUndo {
  private snackBar = inject(MatSnackBar);
  private projects = inject(ProjectStore);

  archive(projectId: string) {
    this.projects.hide(projectId); // the card leaves the board now

    this.snackBar
      .open('Project archived', 'Undo', {duration: 10000})
      .afterDismissed()
      .subscribe(({dismissedByAction}) => {
        if (dismissedByAction) {
          this.projects.show(projectId); // Undo pressed
        } else {
          this.projects.archive(projectId); // timer, replacement or dismiss()
        }
      });
  }
}

go deeper

for a junior

Recall the call: open with a message and an action label, then subscribe to onAction() for the button.

for a middle

Explain afterDismissed() and dismissedByAction, the 0 duration default and the one-at-a-time rule, and how each shapes undo logic.

for a senior

Choose deferred or optimistic commit deliberately, handle rapid repeated actions, and keep an Undo route that does not depend on the snack bar.

for a principal

Set the team's policy for undo versus confirmation, timed versus persistent snack bars, and how that squares with Material's accessibility guidance.

## What `MatSnackBar` gives you `MatSnackBar` is Angular Material's service for **snack bars**: short messages that appear at the edge of the screen (bottom centre by default) and optionally carry one action. In a project tracker, the classic use is the undo affordance after archiving: "Project archived" with an **Undo** button. The service has three ways to open one: - `open(message, action?, config?)` renders Material's built-in text snack bar, - `openFromComponent(Component, config)` renders your component, which reads `MAT_SNACK_BAR_DATA` and can use the `matSnackBarLabel`, `matSnackBarActions` and `matSnackBarAction` directives for consistent styling, - `openFromTemplate(templateRef, config)` renders a template. Each returns a **`MatSnackBarRef`**. ## The reference and its events | Member | What it does | |---|---| | `onAction()` | emits when the action button is pressed | | `afterDismissed()` | emits `{dismissedByAction: boolean}` once the snack bar has gone | | `afterOpened()` | emits once it is visible | | `dismiss()` | closes it from code | | `dismissWithAction()` | closes it as if the action had been pressed | `afterDismissed()` fires for **every** way the snack bar ends: the timer running out, `dismiss()`, another snack bar replacing it, or the action. `dismissedByAction` is what tells them apart. ## Two commit strategies 1. **Deferred commit.** Hide the project from the board at once, but send the archive request only when `afterDismissed()` reports `dismissedByAction: false`. Undo simply puts the card back; nothing reached the server. 2. **Optimistic commit.** Archive on the server at once and, in `onAction()`, send a restore request. The deferred route keeps the server free of churn but loses the archive if the tab closes while the snack bar is up. The optimistic route survives a closed tab but needs a restore operation. Either way the code has to know which event means what. ## Custom snack bar content When the message needs more than one line of text, for example the project name in bold plus Undo and View archive, use `openFromComponent`. The component injects `MAT_SNACK_BAR_DATA` for its values and `MatSnackBarRef` to close itself, and marks its text with `matSnackBarLabel`, its button row with `matSnackBarActions` and each button with `matSnackBarAction`; without those annotations Material treats all of the content as text. A custom Undo button should call `dismissWithAction()`: that makes `onAction()` fire and `afterDismissed()` report `dismissedByAction: true`, so the same undo logic serves built-in and custom snack bars. Material's guidance allows one action plus an optional dismiss or cancel action. ## Defaults that bite - **`duration` defaults to `0`**, which means no timer: the snack bar stays until something dismisses it. Teams often set a global value with `MAT_SNACK_BAR_DEFAULT_OPTIONS`, and the per-call config is spread over it. - **One snack bar at a time.** Opening a new one dismisses the one on screen, and the new one enters after the old one's exit animation. For the deferred strategy that is correct behaviour: archiving project B dismisses A's snack bar with `dismissedByAction: false`, so A commits. - **Position** defaults to `horizontalPosition: 'center'` and `verticalPosition: 'bottom'`. - **`politeness`** defaults to `'polite'`: the message is announced through the CDK's live announcer without interrupting the screen reader. ## Accessibility constraints Material documents - The snack bar **does not move focus** to itself, so a keyboard user may never reach the Undo button before it disappears. - Material's guidance is to **avoid a `duration`** on snack bars that carry an action, because a screen reader user may need time to navigate to it. - Every snack bar action should have **another route**: in a tracker, an "Archived" filter with a Restore button, or a keyboard shortcut. There is a real tension: a timed undo is a common product request, and Material advises against it. The defensible answer is to keep the alternative route and, if a timer is required, make it generous. ## What interviewers listen for - Knowing that `onAction()` and `afterDismissed()` answer different questions. - Knowing the `0` default and the one-at-a-time rule, and what each does to the undo logic. - Not committing inside `onAction()` by mistake: that is the user saying **don't**. - Treating the snack bar as a convenience, never the only path to Undo.

  • The user archives three projects in quick succession; with the deferred strategy, what happens to the first two?
    Each `open()` dismisses the snack bar on screen. The first and second snack bars end with `dismissedByAction: false`, so their `afterDismissed()` handlers commit those archives, and only the third project can still be undone from the snack bar. If all three must stay undoable, the app needs another route, such as a single "3 projects archived" message or an Archived view with Restore.
  • How do you change the default duration for every snack bar in the app?
    Provide `MAT_SNACK_BAR_DEFAULT_OPTIONS` with a config such as `{duration: 5000}`. Each `open()` call spreads its own config over those defaults, so a per-call `duration` still wins. Without the token, the built-in default is `0`, meaning the snack bar stays until something dismisses it.

  • A MatSnackBar disappears after a few seconds by default.
  • Opening a second snack bar queues it until the first one times out.
  • onAction() fires whenever the snack bar is dismissed, by any route.
  • The snack bar moves focus to its Undo button so keyboard users can reach it.
  • Committing the archive inside onAction() is the deferred-commit pattern.