Hello Friends, In this article We will learn how to add the toast notification in an angular project using primeNG.
–First of all, create a new angular app. Now open your terminal and execute the following command on it to install the angular app.
ng new toast-notification
–Then install the following package in your app
npm install primeng --save
The CSS dependencies are as follows the structural CSS of components.
–Now we need to add the CSS files of primeNG into the application at angular.json.
In the angular.json file find the styles array and add the following:
"styles": [ "node_modules/primeicons/primeicons.css", "node_modules/primeng/resources/themes/lara-light-blue/theme.css", "node_modules/primeng/resources/primeng.min.css" ]
Add the below code in App.Module.ts File
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { MessageService } from 'primeng/api'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { ToastModule} from 'primeng/toast' import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, ToastModule ], providers: [ MessageService ], bootstrap: [AppComponent] }) export class AppModule { }
–Now add the below HTML code in the App.Component.html file to add toast notification.
<p-toast></p-toast> <button (click)="warning()">warning</button> <button (click)="error()">error</button> <button (click)="success()">success</button> <button (click)="info()">info</button> <button (click)="custom()">custom</button> <router-outlet></router-outlet>
–Add the below typescript code to the App.Component.ts file.
import { Component } from '@angular/core'; import { MessageService } from 'primeng/api'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private messageService: MessageService) {} warning=()=>{ this.messageService.add({severity:'warn', summary:'warning', detail:'warning message'}) } error=()=>{ this.messageService.add({severity:'error', summary:'error', detail:'error message'}) } success=()=>{ this.messageService.add({severity:'success', summary:'Success', detail:'success message'}) } info=()=>{ this.messageService.add({severity:'info', summary:'info', detail:'info message'}) } custom=()=>{ this.messageService.add({severity:'custom', summary:'custom', detail:'custom message'}) } }
Output:-