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) {
-
- router.events.subscribe(event => {
- if (event instanceof NavigationStart) {
- if (this.keepAfterRouteChange) {
-
- this.keepAfterRouteChange = false;
- } else {
-
- 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);
- }
-
-
- 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.
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.
- import { NgModule } from '@angular/core';
- import { BrowserModule } from '@angular/platform-browser';
- import { NotificationComponent} from './toastr-notification.component';
- import {NotificationService} from './toastr-notification.service';
-
- @NgModule({
- declarations: [
- NotificationComponent
- ],
- imports:[
- BrowserModule
- ],
- exports: [
- NotificationComponent
- ],providers:[
- NotificationService
- ]
- })
- export class NotificationModule
- {
- }
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.
- import { Component } from '@angular/core';
-
- import { NotificationService } from '../shared/component/toastr-notifications/toastr-notification.service';
-
- @Component({
- selector: 'app-counter-component',
- templateUrl: './counter.component.html'
- })
- export class CounterComponent {
-
- constructor(private _notificationservice:NotificationService){
-
- }
-
- public showSuccessNotification(){
- this._notificationservice.success("This is the success message");
- }
-
- public showErrorNotification(){
- this._notificationservice.error("This is the error message");
- }
- }
Step 10
Write a tag of toastr notification in your HTML file of the component where you want to use the notification.
- <toastr-notification></toastr-notification>
Let's create a button and bind the method created in Step 9 to the click event of this button.
- <button (click)="showSuccessNotification()">Success Message</button>
- <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
Image 2