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?
answer
- a config field, an injection token
- same object, not a copy
- Cancel must not change the board
- three type parameters on open
- return a new object, not the input
basics
~20 sPass 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.
solid answer
~40 sThe opener calls `open(EditTaskDialog, { data: task })`, and the dialog reads it with `inject<Task>(MAT_DIALOG_DATA)`. The token is typed `any`, so the type argument on `inject` is what makes it a `Task`. Material provides the very object you passed, not a clone, so binding form fields straight to it would change the board's task even when the user presses Cancel. I seed a form from the data, and on Save build a new task and call `close(updated)` on a `MatDialogRef<EditTaskDialog, Task>`. On the opener side, `open<EditTaskDialog, Task, Task>()` makes `afterClosed()` an `Observable<Task | undefined>`; `undefined` means the user left without saving. Since Material 22 a component dialog can also take the task as a signal input through the `bindings` option.
code
ts · 28 linesimport {Component, inject} from '@angular/core';
import {FormControl, ReactiveFormsModule} from '@angular/forms';
import {MatButton} from '@angular/material/button';
import {MAT_DIALOG_DATA, MatDialogModule, MatDialogRef} from '@angular/material/dialog';
import {Task} from './task';
@Component({
selector: 'app-edit-task-dialog',
imports: [MatDialogModule, MatButton, ReactiveFormsModule],
template: `
<h2 mat-dialog-title>Edit task</h2>
<mat-dialog-content><input [formControl]="title" aria-label="Title" /></mat-dialog-content>
<mat-dialog-actions align="end">
<button matButton (click)="ref.close()">Cancel</button>
<button matButton (click)="save()">Save</button>
</mat-dialog-actions>
`,
})
export class EditTaskDialog {
private readonly task = inject<Task>(MAT_DIALOG_DATA);
readonly ref = inject<MatDialogRef<EditTaskDialog, Task>>(MatDialogRef);
// A copy: typing here never touches the board's task object
readonly title = new FormControl(this.task.title, {nonNullable: true});
save() {
this.ref.close({...this.task, title: this.title.value});
}
}go deeper
Recall that the config's data option reaches the dialog through inject(MAT_DIALOG_DATA), and that close(value) sends a result back.
Explain that the data is the same object reference, why that breaks Cancel, and how open<C, D, R>() and MatDialogRef<C, R> type the two ends.
Show you keep dialogs free of shared mutable state, return new values for the opener to apply, and know when the bindings option replaces the token.
Weigh a convention for dialog contracts across a team: one exported data and result type per dialog, tokens versus bindings, and how results reach the store.
## The data channel A dialog component is created by `MatDialog`, not by a parent template, so it has no parent that could bind its inputs the usual way. The classic channel is the config's **`data`** field: whatever you put there is provided to the dialog under the injection token **`MAT_DIALOG_DATA`** from `@angular/material/dialog`. ```ts this.dialog.open<EditTaskDialog, Task, Task>(EditTaskDialog, {data: task}); ``` ```ts export class EditTaskDialog { readonly task = inject<Task>(MAT_DIALOG_DATA); private ref = inject<MatDialogRef<EditTaskDialog, Task>>(MatDialogRef); } ``` The token itself is declared as `InjectionToken<any>`. The type argument on `inject` is an assertion you make, not something Material checks, so it should match the `D` type you pass to `open()`. ## The trap: it is the same object Material hands the dialog the **exact reference** from the config. There is no clone. That matters as soon as the dialog edits the data: 1. The board renders task cards from an array of task objects. 2. The edit dialog binds its title field directly to `task.title`. 3. The user types a new title, changes their mind and presses **Cancel**. 4. The card behind the backdrop already shows the new title, because the dialog mutated the shared object. The fix is to treat the injected data as **read-only input**: seed a form, a signal or a local copy from it, and on Save produce a **new** object with the changes. The opener decides what to do with that object: replace the task in the store, send it to the API, or ignore it. The same applies one level down: a shallow spread such as `{...task}` copies the top level only, so a dialog that edits `task.checklist` in place still mutates the board's checklist. Copy what you edit, or let a form hold the edited values and assemble the result on Save. ## Typing the result Two generics carry the result type, one on each side: | Side | Declaration | Effect | |---|---|---| | Opener | `open<EditTaskDialog, Task, Task>(...)` | `afterClosed()` is `Observable<Task \| undefined>` | | Dialog | `inject<MatDialogRef<EditTaskDialog, Task>>(MatDialogRef)` | `close()` accepts a `Task` | The opener must spell out all three type parameters because TypeScript cannot infer the result type and does not support partial inference. Neither side checks the other: if the dialog closes with a string, the opener's types are simply wrong. Keeping the result type next to the dialog (an exported `type EditTaskResult = Task`) keeps the two declarations together. The result is **`undefined`** whenever the user leaves without a value: Escape, a backdrop click, or a Cancel button that calls `close()` with nothing. `afterClosed()` emits once and completes, so an opener that prefers `await` can wrap it in RxJS's `firstValueFrom`. ## Signal inputs through `bindings` (Material 22) Since Angular Material 22, `MatDialogConfig` has a **`bindings`** option that applies Angular's dynamic bindings to the component it creates. A dialog can then declare an ordinary signal input: ```ts readonly task = input.required<Task>(); ``` and the opener passes `bindings: [inputBinding('task', () => task)]`, with `inputBinding` from `@angular/core`. The trade-offs: - **Pro:** the dialog looks like any other component, its input is typed by the component itself, and it can be reused outside a dialog. - **Con:** `bindings` does nothing for a dialog opened from a `TemplateRef`, which still reads `data` through `let-data`. - **Same trap:** an input bound to an object still hands over the reference, so the copy-before-editing rule does not go away. ## Related data tokens The same pattern appears across the kit: - `MAT_BOTTOM_SHEET_DATA` for a component opened with `MatBottomSheet`, - `MAT_SNACK_BAR_DATA` for a snack bar opened with `openFromComponent`, - `DIALOG_DATA` from `@angular/cdk/dialog` for the unstyled CDK `Dialog`. Each Material service provides its own token, and because `MatDialog` and `MatBottomSheet` are both built on the CDK `Dialog`, the CDK's `DIALOG_DATA` is provided alongside it with the same value. Injecting another service's Material token, such as `MAT_DIALOG_DATA` inside a bottom sheet, normally fails with a missing-provider error. ## What interviewers probe - Whether you know the data is passed **by reference**, and what that does to Cancel. - Whether you can type both ends, and know the types are not checked across the boundary. - Whether you return a value rather than mutating shared state from inside the dialog. - Whether you know the newer `bindings` route and when it does not apply.
- How would the same dialog take the task through the bindings option instead of MAT_DIALOG_DATA?Declare `task = input.required<Task>()` in the dialog and open it with `bindings: [inputBinding('task', () => task)]`, importing `inputBinding` from `@angular/core`. The option exists since Angular Material 22 and applies only to component dialogs, not `TemplateRef` ones. The object is still shared by reference, so the dialog should still edit a copy.
- Why are the opener's and the dialog's result types not checked against each other?They are two separate generic declarations: `open<C, D, R>()` on one side and `MatDialogRef<C, R>` injected on the other. Nothing connects them at compile time, and `MAT_DIALOG_DATA` is typed `any`. Exporting one result type from the dialog's file and using it in both places is the usual way to keep them aligned.
- What happens if a component opened with MatBottomSheet injects MAT_DIALOG_DATA?Normally a missing-provider error. `MatBottomSheet` provides `MAT_BOTTOM_SHEET_DATA`, `MatDialog` provides `MAT_DIALOG_DATA`, and neither provides the other's token. Both are built on the CDK `Dialog`, so the CDK's `DIALOG_DATA` holds the same data in either; a component meant for both can inject that, or inject each Material token with `{optional: true}`.
Passing data to the dialog is handing someone your original document, not a photocopy: any note they scribble lands on your page even if they then say "never mind". Give them a copy to mark up and take back only the version they hand you.
- MatDialog deep-clones the data, so the dialog can edit it freely.
- MAT_DIALOG_DATA is typed from the config, so no type argument is needed.
- TypeScript infers the result type of afterClosed() from what the dialog closes with.
- A dialog component receives its data through an @Input set by MatDialog automatically.
- Mutating the injected task and closing with nothing is a clean way to save.
Assumes Angular Material 22.2; the dialog's bindings option arrived in 22.0, while data and MAT_DIALOG_DATA work the same in earlier majors.