skip to content

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%

answer

  1. two dismissal routes versus every close
  2. a writable flag on the reference
  3. a synchronous yes-or-no function
  4. back button versus router link
  5. the newest navigation value

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.

solid answer

~40 s

`disableClose: true` stops Escape and backdrop clicks and nothing else: `close()`, `mat-dialog-close` and `closeAll()` still close the dialog. It is also a writable property on `MatDialogRef`, so I can set it only while the form is dirty. `closePredicate`, available since Material 20, is called on every `close()`, including the ones Escape, the backdrop and `closeAll()` trigger, with the result, the config and the component instance; returning `false` cancels that close. It must answer synchronously, so it cannot await a "discard changes?" prompt. `closeOnNavigation` defaults to `true`, which means back and forward only: a router link inside the dialog does not close it. Since 22.2.1 `'url-change'` closes it on any URL change. Navigation disposes the overlay directly, so the predicate is not consulted.

code

ts · 16 lines
ts
import {inject} from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import {EditTaskDialog} from './edit-task-dialog';
import {Task} from './task';

export function openEditTask(task: Task) {
  const dialog = inject(MatDialog);
  return dialog.open<EditTaskDialog, Task, Task | 'discard'>(EditTaskDialog, {
    data: task,
    // Escape, backdrop and closeAll() close with undefined: refuse those while dirty
    closePredicate: (result, _config, instance) =>
      result !== undefined || !(instance as EditTaskDialog | null)?.form.dirty,
    // a router link inside the dialog should close it too (22.2.1+)
    closeOnNavigation: 'url-change',
  });
}

go deeper

for a junior

Recall that disableClose stops Escape and backdrop clicks from closing a MatDialog, and that buttons and close() still work.

for a middle

Explain which exits each of disableClose, closePredicate and closeOnNavigation covers, and that MatDialogRef.disableClose can change at runtime.

for a senior

Guard unsaved edits with a predicate that lets deliberate results through, and know navigation bypasses it and router links need 'url-change' since 22.2.1.

for a principal

Decide where unsaved-change protection lives across the app, in dialog predicates, route guards or autosave, and keep the rules consistent between them.

## The three options in one table An edit-task dialog with a half-written description should not vanish because of a stray Escape. `MatDialogConfig` offers three options that decide when a dialog closes on its own: | Option | Default | Governs | |---|---|---| | `disableClose` | `false` | Escape and backdrop clicks only | | `closePredicate` | none | every call to `close()` on the `MatDialogRef` | | `closeOnNavigation` | `true` | closing when the browser location changes | They look similar and are not: each covers a different set of exits. ## `disableClose`: the two dismissal routes With `disableClose: true`, Escape and a backdrop click do nothing. Everything else still closes the dialog: - a `mat-dialog-close` button, - `dialogRef.close()` from code, - `MatDialog.closeAll()`. It is also a **writable property on `MatDialogRef`**, read at the moment of each key press or click. That lets the dialog turn it on only while there is something to lose: ```ts this.form.valueChanges.subscribe(() => (this.ref.disableClose = this.form.dirty)); ``` Material's accessibility notes warn that disabling Escape breaks the expected `role="dialog"` interaction, which is another reason to scope it to the dirty state. A refused backdrop click does not strand focus on the page: the CDK layer underneath pulls focus back into the dialog. ## `closePredicate`: one gate for every close `closePredicate` was added in Angular Material **20**. It is a function `(result, config, componentInstance) => boolean` that `MatDialogRef.close()` calls before doing anything. Escape, the backdrop, `mat-dialog-close` and `closeAll()` all end in `close()`, so one predicate covers them all. A useful rule for an edit dialog: 1. Save and Discard buttons close with an explicit result, so the predicate lets them through. 2. Escape, the backdrop and `closeAll()` close with `undefined`. 3. The predicate refuses an `undefined` close while the form is dirty. Two limits matter: - It is **synchronous**: it returns a boolean, not a Promise or an observable, so it cannot open a "Discard changes?" dialog and wait. To ask, refuse the close and open the prompt yourself, then call `close()` again from its answer with a result the predicate accepts. - It runs on **every** close attempt, so keep it cheap and free of side effects; a predicate that logs or opens a prompt would do so on each Escape press. - Because `MatDialog.closeAll()` also goes through `close()`, a dirty dialog refuses it too: useful when logout calls `closeAll()`, surprising when a test expects every dialog to be gone. - It does **not** cover navigation, as the next section explains. `MatBottomSheetConfig` has no `closePredicate` at all; the CDK's `DialogConfig` does. ## `closeOnNavigation`: what counts as navigation The default `true` is easy to misread. It is passed to the overlay as `disposeOnNavigation`, and `true` means the same as `'pop-state'`: the dialog closes when the user presses the browser's **back or forward** buttons. Angular's router navigates with `history.pushState`, which fires no `popstate` event, so a `routerLink` *inside* the dialog, say "open the parent project", changes the page behind the backdrop and leaves the dialog open. The values, as of Angular Material 22.2.1: | Value | Closes when | |---|---| | `true` / `'pop-state'` | back or forward is pressed | | `'url-change'` | the URL changes for any reason, router navigation included | | `false` | never, on navigation | `'url-change'` arrived in **22.2.1**. Before it, the fix was to close the dialog yourself, for example by calling `closeAll()` from a router-events subscription. The source warns that `'url-change'` may immediately close an overlay opened from a route resolver, since the URL changes after the resolver runs. Navigation closes the dialog by **disposing its overlay**, not by calling `close()`, so `closePredicate` is not asked: unsaved edits are lost on back, forward or, with `'url-change'`, any navigation. Guarding that needs a router `canDeactivate` guard or a `beforeunload` prompt, outside the dialog's config. ## Putting it together For the edit-task dialog: - a `closePredicate` that refuses `undefined` while dirty, covering Escape, the backdrop and `closeAll()`; - explicit Save and Discard results so deliberate exits pass; - `closeOnNavigation: 'url-change'` if links inside the dialog navigate, accepting that navigation discards edits, or the default plus a route guard if it must not.

  • How do you ask "Discard changes?" when closePredicate cannot wait for an answer?
    Return `false` from the predicate, then open the confirmation yourself, for example by subscribing to `backdropClick()` and `keydownEvents()` on the `MatDialogRef`. If the user confirms, call `close('discard')`, a result the predicate accepts. The predicate stays a pure, synchronous check, and the asynchronous question lives in ordinary event handling.
  • Does disableClose: true stop MatDialog.closeAll() from closing the dialog?
    No. `disableClose` filters only Escape and backdrop clicks. `closeAll()` calls `close()` on every open dialog, so it closes a dialog with `disableClose: true` as well. A `closePredicate`, by contrast, is consulted by that `close()` call and can refuse it.

  • disableClose: true makes the dialog impossible to close except from inside it.
  • closeOnNavigation: true closes the dialog on every router navigation.
  • closePredicate can return a Promise while a confirm dialog asks the user.
  • closePredicate also runs when the dialog closes on back-button navigation.
  • disableClose is fixed at open time and cannot change while the dialog is open.

Assumes Angular Material 22.2.1; closePredicate exists since 20.0, and closeOnNavigation's 'url-change' value arrived in 22.2.1.