A self-contained toast service that any component can inject to show success, error, or info notifications.
// services/toast.service.ts
import { Injectable, signal } from '@angular/core';
export type ToastType = 'success' | 'error' | 'info' | 'warning';
export interface Toast {
id: string;
message: string;
type: ToastType;
}
@Injectable({ providedIn: 'root' })
export class ToastService {
readonly toasts = signal<Toast[]>([]);
show(message: string, type: ToastType = 'info', duration = 3000): void {
const id = crypto.randomUUID();
this.toasts.update(t => [...t, { id, message, type }]);
setTimeout(() => this.dismiss(id), duration);
}
dismiss(id: string): void {
this.toasts.update(t => t.filter(n => n.id !== id));
}
success(msg: string): void { this.show(msg, 'success'); }
error(msg: string): void { this.show(msg, 'error'); }
}
// components/toast-container.component.ts
@Component({
selector: 'app-toast-container',
standalone: true,
template: `
<div class="toast-container">
@for (toast of toastService.toasts(); track toast.id) {
<div [class]="'toast toast-' + toast.type">
{{ toast.message }}
<button (click)="toastService.dismiss(toast.id)">✕</button>
</div>
}
</div>
`,
})
export class ToastContainerComponent {
toastService = inject(ToastService);
}
// Usage in any component
const toast = inject(ToastService);
toast.success('Profile updated!');
toast.error('Something went wrong.');
All Comments