In this Angular Bootstrap tutorial, we are going to learn How to add Toast Messages/ Notification in Angular application using Bootstrap UI components.
Bootstrap is loved by developers for their already built tried and tested UI components, which not only fasten the development tasks but also meet industrial standards.
In Angular projects, we can easily implement Bootstrap UI components by installing the ng-bootstrap package module. The ng-bootstrap package is exclusively developed to use Bootstrap UI components in a reactive web application using Angular 2+ versions.
NgBootstrap provides almost every Bootstrap UI components for the Angular project, we can easily install and configure our project to use Bootstrap components.
We’ll create a new Angular project and learn how to install ng-bootstrap to use Toast UI components with various configuration options properties to modify its style and behavior.
Create a new Angular project
Let’s start with a new Angular project.
Run following NPM command to create a new Angular project using the Ng CLI tool.
$ ng new ng-bootstrap-toast-demo
Install the ng-bootstrap
package
After successfully creating the project, run following NPM command to install the ng-bootstrap
package in the Angular project.
$ npm install --save @ng-bootstrap/ng-bootstrap
The ng-bootstrap includes UI components only, so for adding styling to these components we need to include CSS styling file in the index.html at Angular project root
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" >
Update App Module
Import NgbModule
( Bootstrap module ) & FormsModule
( for Angular as we will use [(ngModel)] )
in the app.module.ts file
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Adding Bootstrap Toasts
Adding a Bootstrap component is a bit tricky, as it is just provided as a DOM component which creates a Toast/ Notification like element. But we need to create our own service to show or hide Toasts messages in our Angular application.
To show a Toast we use NgbToast
directive as shown below:
<ngb-toast header="Notification header">
Content of the notification
</ngb-toast>
Now we will create a Toast component with service to control its behavior.
Create a Toast Service
For the application, we will maintain an array toasts
of Toast notification, in our toast service we will push new Toast messages in that array with their corresponding configuration:
Create the toast
service in _services
folder by running following npm command:
$ ng generate service _services/toast
After creating the service, replace below code in the _services/toast.service.ts file:
// toast.service.ts
import { Injectable, TemplateRef } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ToastService {
toasts: any[] = [];
// Push new Toasts to array with content and options
show(textOrTpl: string | TemplateRef<any>, options: any = {}) {
this.toasts.push({ textOrTpl, ...options });
}
// Callback method to remove Toast DOM element from view
remove(toast) {
this.toasts = this.toasts.filter(t => t !== toast);
}
}
Toast Component
To show toast notification, we will create a toast component, which will have ngb-toast
directive to traverse over notifications from service toast
array.
Run the following command to create a toast component:
$ ng generate component toast
After creating toast.component.ts file, replace it with below code:
// toast.component.ts
import {Component, TemplateRef} from '@angular/core';
import {ToastService} from '../_services/toast.service';
@Component({
selector: 'app-toasts',
template: `
<ngb-toast
*ngFor="let toast of toastService.toasts"
[header]="toast.headertext"
[class]="toast.classname"
[autohide]="toast.autohide"
[delay]="toast.delay || 5000"
(hide)="toastService.remove(toast)"
>
<ng-template [ngIf]="isTemplate(toast)" [ngIfElse]="text">
<ng-template [ngTemplateOutlet]="toast.textOrTpl"></ng-template>
</ng-template>
<ng-template #text>{{ toast.textOrTpl }}</ng-template>
</ngb-toast>
`,
host: {'[class.ngb-toasts]': 'true'}
})
export class ToastComponent {
constructor(public toastService: ToastService) {}
isTemplate(toast) { return toast.textOrTpl instanceof TemplateRef; }
}
The ngb-toast
component directive is having *ngFor
to traverse messages pushed in toasts
array.
The isTemplate
method is checking if toast content is a custom template of string using instanceof
. We have *ngIf else
templates to show content respectively.
There are option properties which we used above:
Properties:
autohide
: Auto-hide the toast after a delay in ms. default: true
delay
: Delay after which the toast will hide (ms). default: 500 (ms)
header
: Text to be used as toast’s header.
Methods:
hide
: An event fired immediately when toast’s hide() method has been called. It can only occur when autohide timeout fires or user clicks on a closing cross.
How to use Toast service and component?
Now we have Toast service and component ready to be used in Angular application. Here we will try to use it from App Component.
Open app.component.html file then add the following template somewhere after router-outlet
:
<app-toasts></app-toasts>
As we added this at application root, so Toast messages will be easily shown over any component’s view.
In app.component.ts file, we will import ToastService
and use its show method by passing strings or templates.
// app.component.ts
import { Component } from '@angular/core';
import { ToastService } from './_services/toast.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'ng-bootstrap-demo';
constructor(
public toastService: ToastService
) {}
showStandard() {
this.toastService.show('I am a standard toast', {
delay: 2000,
autohide: true
});
}
showSuccess() {
this.toastService.show('I am a success toast', {
classname: 'bg-success text-light',
delay: 2000 ,
autohide: true,
headertext: 'Toast Header'
});
}
showError() {
this.toastService.show('I am a success toast', {
classname: 'bg-danger text-light',
delay: 2000 ,
autohide: true,
headertext: 'Error!!!'
});
}
showCustomToast(customTpl) {
this.toastService.show(customTpl, {
classname: 'bg-info text-light',
delay: 3000,
autohide: true
});
}
}
To call these methods and add the toast template, update following code in app component template:
<button class="btn btn-primary" (click)="showStandard()" ngbTooltip="Will disappear in 5s">Standard toast</button>
<button class="btn btn-success" (click)="showSuccess()" ngbTooltip="Will disappear in 10s">Success toast</button>
<button class="btn btn-danger" (click)="showError()" ngbTooltip="Will disappear in 10s">Error toast</button>
<ng-template #customTpl>
<i>This is</i> a <u>custome</u> template <b>toast message</b>
</ng-template>
<button class="btn btn-info" (click)="showCustomToast(customTpl)" ngbTooltip="Will disappear in 15s">Custom toast</button>
<router-outlet></router-outlet>
<app-toasts></app-toasts>
That’s it now you can test these notification toast messages in the browser.
$ ng serve --open
Conclusion
Finally, we have implemented the Bootstrap Toasts messaged in the Angular project using the ng-bootstrap provided directives. You can implement any Bootstrap UI component in the Angular project using the ng-bootstrap package module. Check other useful ng-bootstrap UI components tutorials.
Leave a Reply