Creating a Toast Service with Angular: A Step-by-Step Guide

Chintanonweb
3 min readNov 17, 2023

--

Introduction

Angular is a powerful and popular web application framework that provides a robust structure for building dynamic and responsive web applications. One essential aspect of user interface development is providing feedback to users, and one effective way to do this is through toast notifications. In this article, we’ll explore how to create a toast service in Angular to display non-intrusive notifications to users.

Setting the Stage

Before diving into the code, let’s outline the key steps we’ll be covering:

  1. Creating a Toast Service: We’ll define a service responsible for managing and displaying toast notifications.
  2. Integration with Angular Components: Learn how to integrate the toast service with Angular components to trigger notifications.
  3. Customization Options: Explore ways to customize the appearance and behavior of toast notifications.
  4. FAQ Section: Address common questions and issues that might arise during the implementation.

Creating a Toast Service

Firstly, let’s create the toast service. In your Angular project, open the terminal and run:

ng generate service toast

This command will generate a toast.service.ts file. Open it and define the basic structure of the service.

// toast.service.ts
import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root',
})
export class ToastService {
toasts: string[] = [];

add(message: string) {
this.toasts.push(message);
}

remove(index: number) {
this.toasts.splice(index, 1);
}
}

Here, we’ve created a simple service with methods to add and remove toast messages.

Integration with Angular Components

Now, let’s integrate the toast service with a sample Angular component. For this example, let’s use a button click to trigger a toast notification.

// app.component.ts
import { Component } from '@angular/core';
import { ToastService } from './toast.service';

@Component({
selector: 'app-root',
template: `
<button (click)="showToast()">Show Toast</button>
<div *ngFor="let toast of toastService.toasts; let i = index">
{{ toast }}
<button (click)="removeToast(i)">X</button>
</div>
`,
})
export class AppComponent {

constructor(public toastService: ToastService) {}

showToast() {
this.toastService.add('This is a toast message.');
}

removeToast(index: number) {
this.toastService.remove(index);
}
}

In this component, we’ve added a button to trigger the showToast method, which adds a sample toast message to the ToastService. The toasts are then displayed in the template using Angular's *ngFor directive.

Customization Options

Now, let’s enhance our toast service to allow for customization. We can add options like toast duration, styles, and types.

// toast.service.ts
import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root',
})

export class ToastService {

toasts: { message: string; duration: number; type: 'success' | 'error' }[] = [];

add(message: string, duration: number = 3000, type: 'success' | 'error' = 'success') {
this.toasts.push({ message, duration, type });
setTimeout(() => this.remove(0), duration);
}

remove(index: number) {
this.toasts.splice(index, 1);
}
}

With these modifications, the add method now accepts parameters for message, duration, and type. We've set a default duration of 3000 milliseconds and a default type of 'success'. Additionally, the remove method now includes a timeout to automatically remove the toast after the specified duration.

FAQ Section

Q: How can I customize the appearance of toast messages?

A: The ToastService now includes a type parameter in the add method, allowing you to specify 'success' or 'error'. You can then apply different styles based on the type in your component's template.

Q: Can I change the default duration of toast messages?

A: Yes, the add method accepts a duration parameter, allowing you to set a custom duration for each toast message. The default duration is 3000 milliseconds.

Q: How do I handle user interactions within a toast message?

A: In the component template, you can include buttons or other interactive elements within the toast message. Handle the corresponding events in your component logic.

Wrapping Up

Creating a toast service in Angular provides a clean and reusable way to implement toast notifications in your web applications. By following these steps, you can easily integrate toast notifications with customization options, providing users with valuable feedback without interrupting their workflow. Experiment with different styles and durations to enhance the user experience in your Angular applications.

--

--

Chintanonweb
Chintanonweb

Written by Chintanonweb

As a software engineer, bringing my ideas to life through code and inspiring others with the possibilities. https://chintanonweb.github.io/

No responses yet