Introduction
Today, I am going to show you how to create a notification component, like jQuery toastr in Angular.
Prerequisites
Basic knowledge of Angular components, Services module, and TypeScript.
I will create a custom component for toastr notification. I'll show you how to use that component in your app. I have assumed that you have the basic knowledge of Angular and you have already created an Angular app. Here, I'll show how to create a component in your existing app.
Step 1
Create a folder named toastr-notification in your app's component folder. We will create all the components and services in this folder only.
Step 2
Create a TypeScript file with name 'toastr-notification.model.ts' in the newly created folder in the first step. And, write the code as below in the file. This file is used to create a simple model class to use in the next step.
- export class Notification {
- type: NotificationType;
- message: string;
- }
- export enum NotificationType {
- Success,
- Error,
- Info,
- Warning
- }
Step 3
Create a TypeScript file with the name 'toastr-notification.service.ts' in the toastr-notification folder and into it, paste the code shown below. This file will create the injectable service to show the notification.
Here, we have created the injectable service with observable method which will get the message and its type to show in notification.
- import { Injectable } from '@angular/core';
- import { Router, NavigationStart } from '@angular/router';
- import { Observable, Subject } from 'rxjs';
- import { Notification, NotificationType } from './toastr-notification.model';
- @Injectable()
- export class NotificationService {
- public subject = new Subject<Notification>();
- public keepAfterRouteChange = true;
- constructor(public router: Router) {
- // clear alert messages on route change unless 'keepAfterRouteChange' flag is true
- router.events.subscribe(event => {
- if (event instanceof NavigationStart) {
- if (this.keepAfterRouteChange) {
- // only keep for a single route change
- this.keepAfterRouteChange = false;
- } else {
- // clear alert messages
- this.clear();
- }
- }
- });
- }
- getAlert(): Observable<any> {
- return this.subject.asObservable();
- }
- success(message: string, keepAfterRouteChange = false) {
- this.showNotification(NotificationType.Success, message, keepAfterRouteChange);
- }
- error(message: string, keepAfterRouteChange = false) {
- this.showNotification(NotificationType.Error, message, keepAfterRouteChange);
- }
- info(message: string, keepAfterRouteChange = false) {
- this.showNotification(NotificationType.Info, message, keepAfterRouteChange);
- }
- warn(message: string, keepAfterRouteChange = false) {
- this.showNotification(NotificationType.Warning, message, keepAfterRouteChange);
- }
- showNotification(type: NotificationType, message: string, keepAfterRouteChange = false) {
- this.keepAfterRouteChange = keepAfterRouteChange;
- this.subject.next(<Notification>{ type: type, message: message });
- }
- clear() {
- this.subject.next();
- }
- }
Step 4
Create another TypeScript file with the name 'toastr-notification.component.ts' manually or you can also create a component using Angular CLI and paste the below code in that file. Here, we have created the Notification component and injected the Notification service created in the second step.
- import { Component, OnInit } from '@angular/core';
- import { Notification, NotificationType } from "./toastr-notification.model";
- import { NotificationService } from "./toastr-notification.service";
- @Component({
- selector: 'toastr-notification',
- templateUrl: 'toastr-notification.component.html',
- styleUrls: ['./toastr-notification.component.css']
- })
- export class NotificationComponent {
- notifications: Notification[] = [];
- constructor(public _notificationService: NotificationService) { }
- ngOnInit() {
- this._notificationService.getAlert().subscribe((alert: Notification) => {
- this.notifications = [];
- if (!alert) {
- this.notifications = [];
- return;
- }
- this.notifications.push(alert);
- setTimeout(() => {
- this.notifications = this.notifications.filter(x => x !== alert);
- }, 4000);
- });
- }
- removeNotification(notification: Notification) {
- this.notifications = this.notifications.filter(x => x !== notification);
- }
- /**Set css class for Alert -- Called from alert component**/
- cssClass(notification: Notification) {
- if (!notification) {
- return;
- }
- switch (notification.type) {
- case NotificationType.Success:
- return 'toast-success';
- case NotificationType.Error:
- return 'toast-error';
- case NotificationType.Info:
- return 'toast-info';
- case NotificationType.Warning:
- return 'toast-warning';
- }
- }
- }
Step 5
Create an HTML file with the name 'toastr-notification.component.html' and paste the below code. Here, we have created the template of our component.
- <div id="toast-container" class="toast-top-right" *ngFor="let item of notifications">
- <div class="toast {{cssClass(item) }}" aria-live="polite" style="display: block;">
- <button type="button" class="toast-close-button" role="button" (click)="removeNotification(item)">×</button>
- <div class="toast-message">
- {{item.message}}
- </div>
- </div>
- </div>
Step 6
Now, we will write some CSS to decorate our component. Create a file named 'toastr-notification.component.css' and paste the below code into it.


Join the conversation! Your thoughts help the community grow.