English
Toasts and dialogs
Step 1. The toast service
Why. Many actions end with a short notice: "Profile saved", "Copied to clipboard", "You no longer have access to this chat", or an error from the API. A toast shows it for a few seconds without interrupting the user. Any component or store must be able to show one, so the toasts live in a root service, and one component in the root renders them.
Do. Create the service:
ts
import { Injectable, signal } from '@angular/core';
import { problemMessage } from '../api/problem';
export interface Toast {
id: number;
kind: 'info' | 'success' | 'error';
text: string;
}
/** Short, self-dismissing notices shown by the Toaster component. */
@Injectable({ providedIn: 'root' })
export class ToastService {
private nextId = 1;
readonly toasts = signal<Toast[]>([]);
info(text: string): void {
this.show('info', text);
}
success(text: string): void {
this.show('success', text);
}
/** Shows an error; accepts a message or a failed HTTP response. */
error(error: unknown): void {
this.show('error', typeof error === 'string' ? error : problemMessage(error));
}
dismiss(id: number): void {
this.toasts.update((list) => list.filter((t) => t.id !== id));
}
private show(kind: Toast['kind'], text: string): void {
const id = this.nextId++;
this.toasts.update((list) => [...list.slice(-3), { id, kind, text }]);
setTimeout(() => this.dismiss(id), kind === 'error' ? 6_000 : 3_500);
}
}toastsis a signal holding an array. A signal notices a change only when it gets a new value, soupdatebuilds a new array ([...list, item],filter) instead of pushing into the old one. This immutability is the rule for every signal of collections in Chatex.error(error: unknown)accepts a sentence or anything acatchreceived; for the latter it asksproblemMessageof topic 16 for the text. A component can writecatch (error) { this.toast.error(error); }and the user reads "This chat no longer exists." instead of an HTTP status.- At most four toasts at a time (
slice(-3)keeps the last three, then the new one is added), errors stay 6 seconds, other notices 3.5.
Step 2. The toaster
Why. The component that renders the toasts introduces Angular's control flow blocks, which every template of the following topics uses.
Do. Create the component:
angular-ts
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { ToastService } from '../../core/ui/toast.service';
import { ICONS } from './icons';
@Component({
selector: 'app-toaster',
imports: [ICONS],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div
class="pt-safe pointer-events-none fixed inset-x-0 top-0 z-[1100] flex flex-col items-center gap-2 p-3 sm:top-auto sm:bottom-0 sm:items-end sm:p-6"
aria-live="polite"
>
@for (toast of toasts.toasts(); track toast.id) {
<div
class="pointer-events-auto flex w-full max-w-sm items-start gap-3 rounded-xl border px-4 py-3 text-sm shadow-lg"
[class]="
toast.kind === 'error'
? 'border-red-200 bg-red-50 text-red-800 dark:border-red-900 dark:bg-red-950 dark:text-red-200'
: 'border-line bg-surface text-fg'
"
role="status"
>
@if (toast.kind === 'error') {
<svg lucideCircleExclamationPoint class="mt-0.5 size-4 shrink-0"></svg>
} @else if (toast.kind === 'success') {
<svg lucideCheck class="mt-0.5 size-4 shrink-0 text-emerald-500"></svg>
} @else {
<svg lucideInfo class="mt-0.5 size-4 shrink-0 text-brand-500"></svg>
}
<span class="flex-1">{{ toast.text }}</span>
<button
type="button"
class="-m-1 rounded p-1 opacity-60 hover:opacity-100"
aria-label="Dismiss"
(click)="toasts.dismiss(toast.id)"
>
<svg lucideX class="size-4"></svg>
</button>
</div>
}
</div>
`,
})
export class Toaster {
protected readonly toasts = inject(ToastService);
}@for (toast of toasts.toasts(); track toast.id)repeats the block for each item.tracktells Angular how to recognise an item between renders, like a key in a dictionary: when a toast disappears, Angular removes only its element instead of re-creating the list. Withouttrack, the compiler refuses the template (NG5002: @for loop must have a "track" expression).@if/@else if/@elsepick the icon. These blocks are part of the template syntax since Angular 17 and replace the older*ngIfand*ngFordirectives; they need no imports.[class]="…"binds the class attribute to an expression; static classes inclass="…"and bound ones are merged. Error toasts are red in both themes.aria-live="polite"makes screen readers announce new toasts;role="status"marks each one.- Position. On phones the toasts appear at the top (
top-0), from thesmbreakpoint at the bottom right (sm:top-auto sm:bottom-0 sm:items-end).z-[1100]keeps them above dialogs. The template reads the service's signal directly:toastsisprotectedso that the template, but not other classes, can use it.
Step 3. Dialogs with Angular CDK
Why. Dialogs are hard to get right: focus must move into the dialog and come back when it closes, Esc must close it, the page behind must not scroll, and screen readers must know that it is modal. The Component Dev Kit of the Angular team (@angular/cdk) solves exactly these behaviours without imposing a look — the styling stays ours. Chatex uses its Dialog service here and its menus, clipboard and overlays later.
Do. Create a thin wrapper with Chatex's defaults and a generic confirmation dialog:
angular-ts
import { DIALOG_DATA, Dialog, DialogConfig, DialogRef } from '@angular/cdk/dialog';
import { ComponentType } from '@angular/cdk/portal';
import { ChangeDetectionStrategy, Component, Injectable, inject } from '@angular/core';
import { firstValueFrom } from 'rxjs';
/** Opens app dialogs with shared styling (a centred card that fills the width on phones). */
@Injectable({ providedIn: 'root' })
export class Dialogs {
private readonly dialog = inject(Dialog);
open<R, D, C>(
component: ComponentType<C>,
data?: D,
config: DialogConfig<D, DialogRef<R, C>> = {},
): DialogRef<R, C> {
return this.dialog.open<R, D, C>(component, {
data,
autoFocus: 'first-tabbable',
restoreFocus: true,
backdropClass: 'cdk-overlay-dark-backdrop',
panelClass: 'app-dialog-panel',
maxWidth: '100vw',
...config,
});
}
async confirm(data: ConfirmData): Promise<boolean> {
const ref = this.open<boolean, ConfirmData, ConfirmDialog>(ConfirmDialog, data);
return (await firstValueFrom(ref.closed)) === true;
}
}
export interface ConfirmData {
title: string;
message: string;
confirmText?: string;
danger?: boolean;
}
@Component({
selector: 'app-confirm-dialog',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="dialog-card p-6" role="alertdialog" aria-labelledby="confirm-title">
<h2 id="confirm-title" class="text-lg font-semibold">{{ data.title }}</h2>
<p class="mt-2 text-sm text-muted">{{ data.message }}</p>
<div class="mt-6 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
<button type="button" class="btn-secondary" (click)="ref.close(false)">Cancel</button>
<button
type="button"
[class]="data.danger ? 'btn-danger' : 'btn-primary'"
(click)="ref.close(true)"
>
{{ data.confirmText ?? 'Confirm' }}
</button>
</div>
</div>
`,
})
export class ConfirmDialog {
protected readonly data = inject<ConfirmData>(DIALOG_DATA);
protected readonly ref = inject<DialogRef<boolean>>(DialogRef);
}Dialogs.open(component, data)opens any component as a dialog with the shared options: focus the first focusable element, restore the focus afterwards, a dark backdrop and the panel class ofstyles.css. The generic parameters<R, D, C>are the result type, the data type and the component type, as inDialogRef<R, C>.confirm(...)is the replacement for the browser'sconfirm(): it opensConfirmDialogand turns itsclosedObservable into aPromise<boolean>. A caller writesif (await this.dialogs.confirm({ … })). Closing with Esc or the backdrop yieldsundefined, which counts as "no".ConfirmDialoggets its data through the tokenDIALOG_DATAand closes itself through itsDialogRef.role="alertdialog"andaria-labelledbytell assistive technology what it is.- The CDK positions the dialog with the stylesheet
overlay-prebuilt.css, whichangular.jsonloads before our styles (topic 15).
Step 4. The root component
Do. Add the toaster to the root component, after the router outlet, so that toasts appear above every page:
angular-ts
import { ChangeDetectionStrategy, Component, inject } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ThemeService } from './core/ui/theme.service';
import { Toaster } from './shared/ui/toaster';
@Component({
selector: 'app-root',
imports: [RouterOutlet, Toaster],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<router-outlet /><app-toaster />`,
})
export class App {
constructor() {
// Created eagerly so the saved theme and OS changes apply on every page.
inject(ThemeService);
}
}The root component is now final.
Check
npm run build and npm test -- --watch=false succeed (19 tests). The toasts and dialogs become visible in the next chapters.