typescript 46 lines · 6 steps

A reusable confirmation dialog service in Angular

An injectable service wraps Angular Material dialogs behind a single confirm() method that streams a clean boolean.

Explained by highlit
1import { Injectable, inject } from '@angular/core';
2import { MatDialog } from '@angular/material/dialog';
3import { Observable, of } from 'rxjs';
4import { switchMap } from 'rxjs/operators';
5import { ConfirmDialogComponent } from './confirm-dialog.component';
6 
7export interface ConfirmOptions {
8 title: string;
9 message: string;
10 confirmText?: string;
11 cancelText?: string;
12 destructive?: boolean;
13}
14 
15@Injectable({ providedIn: 'root' })
16export class ConfirmationService {
17 private readonly dialog = inject(MatDialog);
18 
19 confirm(options: ConfirmOptions): Observable<boolean> {
20 const ref = this.dialog.open<ConfirmDialogComponent, ConfirmOptions, boolean>(
21 ConfirmDialogComponent,
22 {
23 width: '420px',
24 autoFocus: options.destructive ? false : 'first-tabbable',
25 restoreFocus: true,
26 data: {
27 confirmText: 'Confirm',
28 cancelText: 'Cancel',
29 destructive: false,
30 ...options,
31 },
32 },
33 );
34 
35 return ref.afterClosed().pipe(switchMap((result) => of(result === true)));
36 }
37 
38 confirmDelete(entity: string): Observable<boolean> {
39 return this.confirm({
40 title: `Delete ${entity}?`,
41 message: `This will permanently remove the ${entity}. This action cannot be undone.`,
42 confirmText: 'Delete',
43 destructive: true,
44 });
45 }
46}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Wrapping a third-party dialog API behind a service keeps callers decoupled from Material specifics.
  2. 2Spreading caller options after your defaults lets you set sensible fallbacks while allowing overrides.
  3. 3Normalizing a dialog result to a strict boolean spares every caller from handling undefined dismissals.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A reusable confirmation dialog service in Angular — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code