How to Create Angular Toastr Notifications
October 11th, 2018 | By Jay Raj | 5 min read
Showing notifications and alerts is a common use case and example regarding web application development.
Today, we will take you on a tour through the Toastr Notifications in Angular web applications.
Note: For this tutorial, we use Angular CLI 6.2.4, @angular/animations 6.1.9, and ngx-toastr 9.1.0.
Getting Started with Angular Application
Let's begin by creating an Angular web application from scratch. To get started, make sure that you have the Angular CLI installed on your system.
npm install -g @angular/cli
Once the Angular CLI has been installed, you can use the ng tool to create an Angular web application.
ng new angular-alert-app
The above CLI command creates a boilerplate Angular web app. Navigate to the project directory and start the web app.
cd angular-alert-app
npm start
You will have the Angular web app running at http://localhost:4200/.
Creating an Angular Component
Let's start from scratch.
Remove the existing default component files from the src/app folder except for app.module.ts.
Create a root component using the Angular CLI tool.
ng generate component root
Remove the AppComponent reference from the app.module.ts and set the RootComponent as the bootstrap component.
Inside the app/root/root.component.html file, add the following HTML code:
<button>
Show Toaster
</button>
Add the following CSS style to the app/root/root.component.css file:
button{
padding: 10px;
margin: 0px;
background-color: red;
border-radius: 100px;
cursor: pointer;
border: 0px;
}
Save the above changes and restart the Angular application. You will be able to see the RootComponent with a button rendered in the web browser.
Adding ngx-toastr to the Angular App
Install ngx-toastr using the Node Package Manager (npm). ngx-toastr also requires the @angular/animation package as a dependency.
npm install ngx-toastr --save
npm install @angular/animations --save
Once you have installed the above packages, open the <project-directory>/angular.json file and include the toastr CSS.
"styles": [
"src/styles.css",
"node_modules/ngx-toastr/toastr.css"
]
Include the BrowserAnimationsModule and ToastrModule in the app.module.ts file and import both modules.
Here is how the app.module.ts file looks:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';
import { RootComponent } from './root/root.component';
@NgModule({
declarations: [
RootComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
ToastrModule.forRoot()
],
providers: [],
bootstrap: [RootComponent]
})
export class AppModule { }
In order to use the ngx-toastr module, you need to include the ToastrService in the RootComponent.
import { ToastrService } from 'ngx-toastr';
Instantiate the ToastrService in the RootComponent's constructor method. Define a method to show the Toast message. Inside the method, initiate the success method of the ToastrService instance.
Here is how the root.component.ts file should look:
import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
@Component({
selector: 'app-root',
templateUrl: './root.component.html',
styleUrls: ['./root.component.css']
})
export class RootComponent implements OnInit {
constructor(private toastr: ToastrService) { }
ngOnInit() {
}
showToaster(){
this.toastr.success("Hello, I'm the toastr message.")
}
}
Then, add the click handler to the button inside the root.component.html file.
<button (click)="showToaster()">
Show Toaster
</button>
Save the above changes and restart the server. Click on the Show Toaster button when running the application on http://localhost:4200/. You will be able to view the toast message.
Adding a Custom Wrapper
Whenever you use an external module in your web application, it is always recommended to write a wrapper for it. Writing a wrapper makes sure that, in the event that, at some point in the future, you need to replace the third-party module, it doesn't break your application or require a lot of rewrites.
Let's have a look at how you can add a wrapper for ngx-toastr in your Angular application.
Create an Angular service called notification, which you'll use in your application to show the toastr message. In src/app, create a folder called utility. Navigate to the utility folder and create an Angular service.
ng generate service notification
Import the ngx-toastr service inside the NotificationService. Create a method called showSuccess to show success notification toasts. The notification.service.ts file should look similar to this:
import { Injectable } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
@Injectable({
providedIn: 'root'
})
export class NotificationService {
constructor(private toastr: ToastrService) { }
showSuccess(message, title){
this.toastr.success(message, title)
}
}
Import the NotificationService wrapper inside the RootComponent and call the showSuccess method to show toast messages.
Here is how the root.component.ts file looks:
import { Component, OnInit } from '@angular/core';
import { NotificationService } from '../utility/notification.service'
@Component({
selector: 'app-root',
templateUrl: './root.component.html',
styleUrls: ['./root.component.css']
})
export class RootComponent implements OnInit {
constructor(private notifyService : NotificationService) { }
ngOnInit() {
}
showToaster(){
this.notifyService.showSuccess("Data shown successfully !!", "Notification")
}
}
If you need to replace ngx-toastr with any other module, you only need to modify the NotificationService. No other part of the application needs any changes.
Customizing The Toast Notification
ngx-toastr provides a number of options to customize the toast notification. You can control how you want the toast notification to render. Find more information about customizing the Toast Notification in the NPM official docs.
Adding HTML Content Inside Toast
ngx-toastr provides an option to add HTML code inside the toast message. To enable it to use HTML content inside the toast notification, you need to use the enableHtml option.
Add a new method inside the notification.service.ts file to render HTML inside the toast notification, as shown:
showHTMLMessage(message, title){
this.toastr.success(message, title, {
enableHtml : true
})
}
With a click of a button, you will have the HTML content displayed inside the toaster notification.
showHtmlToaster(){
this.notifyService.showHTMLMessage("<h2>Data shown successfully !!</h2>", "Notification")
}
Control Notification Display Time
ngx-toastr also provides an option to control the time for which the notification is displayed. You can increase or decrease the time by using the timeOut option. The time unit here is milliseconds.
showSuccessWithTimeout(message, title, timespan){
this.toastr.success(message, title ,{
timeOut : timespan
})
}
Final lessons from the tutorial
You have learned how to use ngx-toastr to show toast notifications in an Angular web application.
For detailed information on ngx-toastr, we recommend reading the official documentation above.
The source code for this tutorial is available on GitHub resources from the Jscrambler blog.
If you're building applications with sensitive logic, be sure to protect them against code theft and reverse engineering by following our guide explaining how to integrate Jscrambler seamlessly into Angular's build process in just a few minutes.
Jscrambler
The leader in client-side Web security. With Jscrambler, JavaScript applications become self-defensive and capable of detecting and blocking client-side attacks like Magecart.
View All ArticlesMust read next
Implementing React Native Push Notifications in Android Apps
Push notifications are still one of the best ways to get mobile app engagement. Learn to set them up in your React Native project by following this guide.
May 19, 2021 | By Aman Mittal | 8 min read
How To Build Authentication in Angular Using Node and Passport
Passport.js provides a simple authentication middleware that you can use with Node.js. Learn how to use it to easily add authentication to your Angular app.
October 17, 2019 | By Jay Raj | 7 min read