Toastr Like Notification Component In Angular 7

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.
  1. export class Notification {  
  2.     type: NotificationType;  
  3.     message: string;  
  4. }  
  5. export enum NotificationType {  
  6.     Success,  
  7.     Error,  
  8.     Info,  
  9.     Warning  
  10. }  

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.
  1. import { Injectable } from '@angular/core';  
  2. import { Router, NavigationStart } from '@angular/router';  
  3. import { Observable, Subject } from 'rxjs';  
  4.   
  5.   
  6. import { Notification, NotificationType } from './toastr-notification.model';  
  7.   
  8. @Injectable()  
  9. export class NotificationService {  
  10.     public subject = new Subject<Notification>();  
  11.     public keepAfterRouteChange = true;  
  12.   
  13.     constructor(public router: Router) {  
  14.         // clear alert messages on route change unless 'keepAfterRouteChange' flag is true  
  15.         router.events.subscribe(event => {  
  16.             if (event instanceof NavigationStart) {  
  17.                 if (this.keepAfterRouteChange) {  
  18.                     // only keep for a single route change  
  19.                     this.keepAfterRouteChange = false;  
  20.                 } else {  
  21.                     // clear alert messages  
  22.                     this.clear();  
  23.                 }  
  24.             }  
  25.         });  
  26.     }  
  27.   
  28.     getAlert(): Observable<any> {  
  29.         return this.subject.asObservable();  
  30.     }  
  31.   
  32.     success(message: string, keepAfterRouteChange = false) {  
  33.         this.showNotification(NotificationType.Success, message, keepAfterRouteChange);  
  34.     }  
  35.   
  36.     error(message: string, keepAfterRouteChange = false) {  
  37.         this.showNotification(NotificationType.Error, message, keepAfterRouteChange);  
  38.     }  
  39.   
  40.     info(message: string, keepAfterRouteChange = false) {  
  41.         this.showNotification(NotificationType.Info, message, keepAfterRouteChange);  
  42.     }  
  43.   
  44.     warn(message: string, keepAfterRouteChange = false) {  
  45.         this.showNotification(NotificationType.Warning, message, keepAfterRouteChange);  
  46.     }  
  47.   
  48.     showNotification(type: NotificationType, message: string, keepAfterRouteChange = false) {  
  49.         this.keepAfterRouteChange = keepAfterRouteChange;  
  50.         this.subject.next(<Notification>{ type: type, message: message });  
  51.     }  
  52.   
  53.     clear() {  
  54.         this.subject.next();  
  55.     }  
  56. }  
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.
  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. import { Notification, NotificationType } from "./toastr-notification.model";  
  4. import { NotificationService } from "./toastr-notification.service";  
  5.   
  6. @Component({  
  7.     selector: 'toastr-notification',  
  8.     templateUrl: 'toastr-notification.component.html',  
  9.     styleUrls: ['./toastr-notification.component.css']  
  10. })  
  11.   
  12. export class NotificationComponent {  
  13.     notifications: Notification[] = [];  
  14.   
  15.     constructor(public _notificationService: NotificationService) { }  
  16.   
  17.     ngOnInit() {  
  18.         this._notificationService.getAlert().subscribe((alert: Notification) => {  
  19.             this.notifications = [];  
  20.             if (!alert) {  
  21.                 this.notifications = [];  
  22.                 return;  
  23.             }  
  24.             this.notifications.push(alert);  
  25.             setTimeout(() => {  
  26.                 this.notifications = this.notifications.filter(x => x !== alert);  
  27.             }, 4000);  
  28.         });  
  29.     }  
  30.   
  31.     removeNotification(notification: Notification) {  
  32.         this.notifications = this.notifications.filter(x => x !== notification);  
  33.     }  
  34.   
  35.     /**Set css class for Alert -- Called from alert component**/      
  36.     cssClass(notification: Notification) {  
  37.         if (!notification) {  
  38.             return;  
  39.         }  
  40.         switch (notification.type) {  
  41.             case NotificationType.Success:  
  42.                 return 'toast-success';  
  43.             case NotificationType.Error:  
  44.                 return 'toast-error';  
  45.             case NotificationType.Info:  
  46.                 return 'toast-info';  
  47.             case NotificationType.Warning:  
  48.                 return 'toast-warning';  
  49.         }  
  50.     }  
  51. }  
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.
  1. <div id="toast-container" class="toast-top-right" *ngFor="let item of notifications">  
  2.     <div class="toast {{cssClass(item) }}" aria-live="polite" style="display: block;">  
  3.         <button type="button" class="toast-close-button" role="button" (click)="removeNotification(item)">×</button>  
  4.         <div class="toast-message">  
  5.             {{item.message}}  
  6.         </div>  
  7.     </div>  
  8. </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.  
  1. .toast-title {  
  2.     font-weight: bold;  
  3. }  
  4.   
  5. .toast-message {  
  6.     word-wrap: break-word;  
  7. }  
  8.   
  9.     .toast-message a,  
  10.     .toast-message label {  
  11.         color: #FFFFFF;  
  12.     }  
  13.   
  14.         .toast-message a:hover {  
  15.             color: #CCCCCC;  
  16.             text-decoration: none;  
  17.         }  
  18.   
  19. .toast-close-button {  
  20.     position: relative;  
  21.     right: -0.3em;  
  22.     top: -0.3em;  
  23.     float: right;  
  24.     font-size: 20px;  
  25.     font-weight: bold;  
  26.     color: #FFFFFF;  
  27.     -webkit-text-shadow: 0 1px 0 #ffffff;  
  28.     text-shadow: 0 1px 0 #ffffff;  
  29.     opacity: 0.8;  
  30. }  
  31.   
  32.     .toast-close-button:hover,  
  33.     .toast-close-button:focus {  
  34.         color: #000000;  
  35.         text-decoration: none;  
  36.         cursor: pointer;  
  37.         opacity: 0.4;  
  38.     }  
  39. /*Additional properties for button version 
  40.  iOS requires the button element instead of an anchor tag. 
  41.  If you want the anchor version, it requires `href="#"`.*/  
  42. button.toast-close-button {  
  43.     padding: 0;  
  44.     cursor: pointer;  
  45.     background: transparent;  
  46.     border: 0;  
  47.     -webkit-appearance: none;  
  48. }  
  49.   
  50. .toast-top-center {  
  51.     top: 0;  
  52.     right: 0;  
  53.     width: 100%;  
  54. }  
  55.   
  56. .toast-bottom-center {  
  57.     bottom: 0;  
  58.     right: 0;  
  59.     width: 100%;  
  60. }  
  61.   
  62. .toast-top-full-width {  
  63.     top: 0;  
  64.     right: 0;  
  65.     width: 100%;  
  66. }  
  67.   
  68. .toast-bottom-full-width {  
  69.     bottom: 0;  
  70.     right: 0;  
  71.     width: 100%;  
  72. }  
  73.   
  74. .toast-top-left {  
  75.     top: 12px;  
  76.     left: 12px;  
  77. }  
  78.   
  79. .toast-top-right {  
  80.     top: 12px;  
  81.     right: 12px;  
  82. }  
  83.   
  84. .toast-bottom-right {  
  85.     right: 12px;  
  86.     bottom: 12px;  
  87. }  
  88.   
  89. .toast-bottom-left {  
  90.     bottom: 12px;  
  91.     left: 12px;  
  92. }  
  93.   
  94. #toast-container {  
  95.     pointer-events: none;  
  96.     position: fixed;  
  97.     z-index: 99999;  
  98. }  
  99.   
  100.     #toast-container * {  
  101.         -moz-box-sizing: border-box;  
  102.         -webkit-box-sizing: border-box;  
  103.         box-sizing: border-box;  
  104.     }  
  105.   
  106.     #toast-container > div {  
  107.         position: relative;  
  108.         overflow: hidden;  
  109.         margin: 0 0 6px;  
  110.         padding: 15px 15px 15px 50px;  
  111.         width: 300px;  
  112.         -moz-border-radius: 3px 3px 3px 3px;  
  113.         -webkit-border-radius: 3px 3px 3px 3px;  
  114.         border-radius: 3px 3px 3px 3px;  
  115.         background-position: 15px center;  
  116.         background-repeat: no-repeat;  
  117.         -moz-box-shadow: 0 0 12px #999999;  
  118.         -webkit-box-shadow: 0 0 12px #999999;  
  119.         box-shadow: 0 0 12px #999999;  
  120.         color: #FFFFFF;  
  121.         opacity: 0.8;  
  122.     }  
  123.   
  124.         #toast-container > div.toast-custom {  
  125.             padding: 15px;  
  126.             color: #030303;  
  127.         }  
  128.   
  129.             #toast-container > div.toast-custom .toast-close-button {  
  130.                 color: #999999 !important;  
  131.             }  
  132.   
  133.     #toast-container > :hover {  
  134.         -moz-box-shadow: 0 0 12px #000000;  
  135.         -webkit-box-shadow: 0 0 12px #000000;  
  136.         box-shadow: 0 0 12px #000000;  
  137.         opacity: 1;  
  138.         cursor: pointer;  
  139.     }  
  140.   
  141.     #toast-container > .toast-info {  
  142.         background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGwSURBVEhLtZa9SgNBEMc9sUxxRcoUKSzSWIhXpFMhhYWFhaBg4yPYiWCXZxBLERsLRS3EQkEfwCKdjWJAwSKCgoKCcudv4O5YLrt7EzgXhiU3/4+b2ckmwVjJSpKkQ6wAi4gwhT+z3wRBcEz0yjSseUTrcRyfsHsXmD0AmbHOC9Ii8VImnuXBPglHpQ5wwSVM7sNnTG7Za4JwDdCjxyAiH3nyA2mtaTJufiDZ5dCaqlItILh1NHatfN5skvjx9Z38m69CgzuXmZgVrPIGE763Jx9qKsRozWYw6xOHdER+nn2KkO+Bb+UV5CBN6WC6QtBgbRVozrahAbmm6HtUsgtPC19tFdxXZYBOfkbmFJ1VaHA1VAHjd0pp70oTZzvR+EVrx2Ygfdsq6eu55BHYR8hlcki+n+kERUFG8BrA0BwjeAv2M8WLQBtcy+SD6fNsmnB3AlBLrgTtVW1c2QN4bVWLATaIS60J2Du5y1TiJgjSBvFVZgTmwCU+dAZFoPxGEEs8nyHC9Bwe2GvEJv2WXZb0vjdyFT4Cxk3e/kIqlOGoVLwwPevpYHT+00T+hWwXDf4AJAOUqWcDhbwAAAAASUVORK5CYII=") !important;  
  143.     }  
  144.   
  145.     #toast-container > .toast-error {  
  146.         background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHOSURBVEhLrZa/SgNBEMZzh0WKCClSCKaIYOED+AAKeQQLG8HWztLCImBrYadgIdY+gIKNYkBFSwu7CAoqCgkkoGBI/E28PdbLZmeDLgzZzcx83/zZ2SSXC1j9fr+I1Hq93g2yxH4iwM1vkoBWAdxCmpzTxfkN2RcyZNaHFIkSo10+8kgxkXIURV5HGxTmFuc75B2RfQkpxHG8aAgaAFa0tAHqYFfQ7Iwe2yhODk8+J4C7yAoRTWI3w/4klGRgR4lO7Rpn9+gvMyWp+uxFh8+H+ARlgN1nJuJuQAYvNkEnwGFck18Er4q3egEc/oO+mhLdKgRyhdNFiacC0rlOCbhNVz4H9FnAYgDBvU3QIioZlJFLJtsoHYRDfiZoUyIxqCtRpVlANq0EU4dApjrtgezPFad5S19Wgjkc0hNVnuF4HjVA6C7QrSIbylB+oZe3aHgBsqlNqKYH48jXyJKMuAbiyVJ8KzaB3eRc0pg9VwQ4niFryI68qiOi3AbjwdsfnAtk0bCjTLJKr6mrD9g8iq/S/B81hguOMlQTnVyG40wAcjnmgsCNESDrjme7wfftP4P7SP4N3CJZdvzoNyGq2c/HWOXJGsvVg+RA/k2MC/wN6I2YA2Pt8GkAAAAASUVORK5CYII=") !important;  
  147.     }  
  148.   
  149.     #toast-container > .toast-success {  
  150.         background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg==") !important;  
  151.     }  
  152.   
  153.     #toast-container > .toast-warning {  
  154.         background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGYSURBVEhL5ZSvTsNQFMbXZGICMYGYmJhAQIJAICYQPAACiSDB8AiICQQJT4CqQEwgJvYASAQCiZiYmJhAIBATCARJy+9rTsldd8sKu1M0+dLb057v6/lbq/2rK0mS/TRNj9cWNAKPYIJII7gIxCcQ51cvqID+GIEX8ASG4B1bK5gIZFeQfoJdEXOfgX4QAQg7kH2A65yQ87lyxb27sggkAzAuFhbbg1K2kgCkB1bVwyIR9m2L7PRPIhDUIXgGtyKw575yz3lTNs6X4JXnjV+LKM/m3MydnTbtOKIjtz6VhCBq4vSm3ncdrD2lk0VgUXSVKjVDJXJzijW1RQdsU7F77He8u68koNZTz8Oz5yGa6J3H3lZ0xYgXBK2QymlWWA+RWnYhskLBv2vmE+hBMCtbA7KX5drWyRT/2JsqZ2IvfB9Y4bWDNMFbJRFmC9E74SoS0CqulwjkC0+5bpcV1CZ8NMej4pjy0U+doDQsGyo1hzVJttIjhQ7GnBtRFN1UarUlH8F3xict+HY07rEzoUGPlWcjRFRr4/gChZgc3ZL2d8oAAAAASUVORK5CYII=") !important;  
  155.     }  
  156.   
  157.     #toast-container.toast-top-center > div,  
  158.     #toast-container.toast-bottom-center > div {  
  159.         width: 300px;  
  160.         margin: auto;  
  161.     }  
  162.   
  163.     #toast-container.toast-top-full-width > div,  
  164.     #toast-container.toast-bottom-full-width > div {  
  165.         width: 96%;  
  166.         margin: auto;  
  167.     }  
  168.   
  169. .toast {  
  170.     background-color: #FFFFFF;  
  171.     pointer-events: auto;  
  172. }  
  173.   
  174. .toast-success {  
  175.     background-color: #51A351;  
  176. }  
  177.   
  178. .toast-error {  
  179.     background-color: #BD362F;  
  180. }  
  181.   
  182. .toast-info {  
  183.     background-color: #2F96B4;  
  184. }  
  185.   
  186. .toast-warning {  
  187.     background-color: #F89406;  
  188. }  
  189.   
  190. .toast-progress {  
  191.     position: absolute;  
  192.     left: 0;  
  193.     bottom: 0;  
  194.     height: 4px;  
  195.     background-color: #000000;  
  196.     opacity: 0.4;  
  197. }  
  198.   
  199. /*Responsive Design*/  
  200. @media all and (max-width: 240px) {  
  201.     #toast-container > div {  
  202.         padding: 8px 8px 8px 50px;  
  203.         width: 11em;  
  204.     }  
  205.   
  206.     #toast-container .toast-close-button {  
  207.         right: -0.2em;  
  208.         top: -0.2em;  
  209.     }  
  210. }  
  211.   
  212. @media all and (min-width: 241px) and (max-width: 480px) {  
  213.     #toast-container > div {  
  214.         padding: 8px 8px 8px 50px;  
  215.         width: 18em;  
  216.     }  
  217.   
  218.     #toast-container .toast-close-button {  
  219.         right: -0.2em;  
  220.         top: -0.2em;  
  221.     }  
  222. }  
  223.   
  224. @media all and (min-width: 481px) and (max-width: 768px) {  
  225.     #toast-container > div {  
  226.         padding: 15px 15px 15px 50px;  
  227.         width: 25em;  
  228.     }  
  229. }  
Step 7
 
Our Toastr Notification component is almost ready. Now, we will create a module and will declare this component in that module. So, we can declare this module in any other module where we want to use this component or in 'app.module.ts' file. 
  1. import { NgModule } from '@angular/core';    
  2. import { BrowserModule } from '@angular/platform-browser';  
  3. import { NotificationComponent} from './toastr-notification.component';    
  4. import {NotificationService} from './toastr-notification.service';    
  5.     
  6. @NgModule({    
  7.     declarations: [    
  8.         NotificationComponent    
  9.     ],  
  10.     imports:[  
  11.         BrowserModule  
  12.     ],  
  13.     exports: [    
  14.         NotificationComponent    
  15.     ],providers:[    
  16.         NotificationService    
  17.     ]    
  18. })    
  19. export class NotificationModule    
  20. {    
  21. }    
Step 8
 
Our Component is ready now. Let's import the module file created in the above step into our app.module.ts file.
 
Now, we can use our Notification component in any of the other components. To use this component in another component, we need to follow the following steps.
 
To use the component, we have to import the NotificationModule from 'toastr.notification.module.ts' file in app.module.ts.
 
Note
You can import NotificationModule in any module you want to use.
 
Step 9
 
Let's assume we are using this component in another component. To use the above-created component, we have to inject the service created above in the constructor of this component. See line no. 03 and 11 in the code below.
  1. import { Component } from '@angular/core';  
  2.   
  3. import { NotificationService } from '../shared/component/toastr-notifications/toastr-notification.service';  
  4.   
  5. @Component({  
  6.   selector: 'app-counter-component',  
  7.   templateUrl: './counter.component.html'  
  8. })  
  9. export class CounterComponent {  
  10.     
  11.   constructor(private _notificationservice:NotificationService){  
  12.   
  13.   }  
  14.   
  15.   public showSuccessNotification(){  
  16.     this._notificationservice.success("This is the success message");  
  17.   }  
  18.   
  19.   public showErrorNotification(){  
  20.     this._notificationservice.error("This is the error message");  
  21.   }  
  22. }  
Step 10 
 
Write a tag of toastr notification in your HTML file of the component where you want to use the notification.
  1. <toastr-notification></toastr-notification>  
Let's create a button and bind the method created in Step 9  to the click event of this button.
  1. <button (click)="showSuccessNotification()">Success Message</button>  
  2. <button (click)="showErrorNotification()">Error Message</button>  
Now, run the app and click the button. You will see the notification as shown in the images below.
 
Image 1
 
Toastr Like Notification Component In Angular 7 
 
Image 2
 
Toastr Like Notification Component In Angular 7


Similar Articles