Primeng toast example | Angular Popup component


Toast is a UI component interactive popup window for showing the progress of an application. Popup will be hidden automatically after a timeout.

Toast in an application is a popup window on main DOM page.

In An application, Toast UI is shown to the user for the following use case

  • Authentication successful
  • Give useful message for Server validation errors -  Duplicate records,
  • Domain operation results message like the record is deleted from a database.- Confirm popup window to delete record

Primeng provides a lot of useful UI components in Angular. Toast is one of the components that used to display interactive messages in the overlay.

These tutorials cover Primeng Angular popup example but not covered how to create an angular application.

Primeng NPM install dependencies

Once your angular application ready to work on , Please install npm dependencies

Primeng has following dependencies to integrate into an angular application

Primeng npm  module contains actual UI components, themes primeicons npm module provides all the icons for primeng UI library

Installation can be done in one of two always One step is to install required dependencies npm install primeng command,

This will create required dependencies in node_modules folder and also add entries in package.json

npm install --save primeng
npm install --save primeicons

And other ways is to provide dependencies in package.json

"primeicons": "^2.0.0",
"primeng": "9.0.6",

Please issue npm install in the application root directory.

Once dependencies are installed, Next is to add Primeng CSS styles to your application

update styles to angular.json

There is an angular.json file located in the root directory of the angular application.

Angular.json has required configuration information related to styles, scripts, and required module configuration for lint, build and production builds.

Once you installed dependencies, primeng CSS files are located in “./node_modules/primeng/” for primeng and “./node_modules/primeicons” for primeicons.

styles in angular.json provide global access primeng styles to all your components in angular application.

here configured primeicons.css for primeng fonts, luna-blue is the primeng theme and primeng.min.css for required CSS styles for components.

"styles": [
  "./node_modules/primeicons/primeicons.css",
  "./node_modules/primeng/resources/themes/luna-blue/theme.css",
  "./node_modules/primeng/resources/primeng.min.css"
  ]
  ```

## import ToastModule into angular NgModule

If you want to access internal or external components, You need to import the module into your application module.
Primeng provides toast components in `ToastModule`
And also includes MessageService in the provider section of the application module, so that MessageService is in global scope and accessible across components of an application.

MessageService is an API Service for

```javascript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import {  ToastModule, MessageService, ButtonModule } from 'primeng';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app.routing.module';

@NgModule({
  imports:      [ AppRoutingModule,BrowserModule,BrowserAnimationsModule, ToastModule,ButtonModule],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent ],
  providers:[MessageService],
})
export class AppModule { }

p-toast button click examples

Create a basic component

In the template component, place p-toast component inside it Html template component

<p>
	Basic toast example
</p>

<p-toast></p-toast>

<button type="button" pButton (click)="showMessage()" label="Simple Toast Example" class="ui-button-success"></button>

Typescript code

import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng';

@Component({
  selector: 'app-basic-toast',
  templateUrl: './basic-toast.component.html',
  styleUrls: ['./basic-toast.component.css']
})
export class BasicToastComponent implements OnInit {

      constructor(private messageService: MessageService) {}
    showMessage() {
        this.messageService.add({severity:'info', summary: 'Record is added successully', detail:'record added'});
    }
  ngOnInit() {
  }

}

Adding an object to messageService, OBject content three fields

Severity of toast message type, the Following severity types are supported.

  • success - successful message type like record added
  • info like loading few more records
  • warn as duplicate records exist
  • error like a server error
  • custom like  custom error

A summary is the title of toast message for Popup the detail is the subtitle of toast popup

Output displayed in the browser

Angular primeng toast example

toast position

By default, toast popup is shown in the top right position

This can be controlled using the position attribute.

position possible values are

  • top-left
  • top-center
  • center
  • bottom-center
  • bottom-left
  • bottom-right

Created ToastPositionComponent for showing error popup in top center ToastPositionComponent

import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng';

@Component({
  selector: 'app-toast-position',
  templateUrl: './toast-position.component.html',
  styleUrls: ['./toast-position.component.css']
})
export class ToastPositionComponent implements OnInit {

       constructor(private messageService: MessageService) {}
    showError() {
        this.messageService.add({severity:'error', summary: 'Server error', detail:'500 error'});
    }
  ngOnInit() {
  }
}

In the Html template, position attribute is added

<p>
	 toast position example
</p>

<p-toast position="top-center"></p-toast>

<button type="button"  pButton (click)="showError()" label=" Toast position Example" class="ui-button-error"></button>

manually remove toast clear method

By default popup shows for period of time,

We can remove the toast using programmatically

In html template components

<button type="button" pButton (click)="remove()" label="Remove"></button>

in typescript code, call clearn method of MessageService

this.messageService.clear();

customize styles

toast CSS can be customized by using default CSS selector as well as custom selector default, CSS selector,

  • ui-toast - It is a popup window styles
  • ui-toast-message - This overrides the message content styles
  • ui-toast-detail - This overrides message detail styles The below css styles is to change font-family and color of the toast message content
.newfont-styles .ui-toast-message {
font-family: 'proxima nova';
color:"red"
}

To change the width of toast popup

:host ::ng-deep .newfont-styles .ui-toast {
    display: flex;
    width:70%;
}

Add css selector using class attribute to p-toast component.

<p-toast class="newfont-styles"></p-toast>

HTML content

The below example illustrates about following things

  • Created ToastHtmlComponent
  • In the component, toast content contains html content not text htmlContent
  • using ng-template inside p-toast component
  • add innerHtml to div tag inside ng-templates
import { Component, OnInit } from "@angular/core";
import { MessageService } from "primeng";

@Component({
  selector: "app-toast-html",
  templateUrl: "./toast-html.component.html",
  styleUrls: ["./toast-html.component.css"]
})
export class ToastHtmlComponent implements OnInit {
  htmlContent: string = "";

  showHtmlContent(descreption) {
    this.htmlContent = "<h1>Heading 1<h1>\n<h2>Heading 2<h2>";
    this.messageService.add({
      severity: "info",
      summary: "Summary content",
      detail: ""
    });
  }

  constructor(private messageService: MessageService) {}

  ngOnInit() {}
}
<p>
	HTML content toast example
</p>
<p-toast position="top-center">
	<ng-template let-message pTemplate="message">
		<div innerHtml="{{htmlContent}}">
		</div>
	</ng-template>
</p-toast>
<button type="button" pButton (click)="showHtmlContent()" label="Toast html content Example" class="ui-button-success"></button>

And the output is

Angular primeng toast html content example

delete confirm toast popup window

Sometimes, we have a data table in an application, the user needs to notify the message during successful  CRUD operations,

IN the below example talks how to show confirm windows to ask for user yes or no based on user pinterest_domain_verification

For example, In the table of records, you will ask confirm window to delete a record,

Confirm window will be shown to the user, if user click yes, the popup disappears and calls API for deleting records from a Database, if the user click no, popup closes do nothing.

onYes() {
    this.messageService.clear('r');
// call  delete Service API to record from database
}
onNo() {
    this.messageService.clear('r');
}
<p-toast position="center" key="r" (onClose)="onNo()" [modal]="true" [baseZIndex]="1000">
    <ng-template let-content pTemplate="content">
        <div style="text-align: center">
            <h3>{{content.summary}}</h3>
            <p>{{content.detail}}</p>
        </div>
        <div class="ui-g ui-fluid">
            <div class="ui-g-6">
                <button type="button" pButton (click)="onYes()" label="Yes" class="ui-button"></button>
            </div>
            <div class="ui-g-6">
                <button type="button" pButton (click)="onNo()" label="No" class="ui-button"></button>
            </div>
        </div>
    </ng-template>
</p-toast>

Angular primeng toast errors

The below section talks about various errors that used to occur during primeng toast usages

p-toast is not a known element

This is a common error that happens for every developer during angular coding.

p-toast component element is used in the HTML template, the element is not able to recognize.

The fix for the issue is

  •  Please make sure that primeng is installed correctly, Check package.json has required primeng dependencies and node_modules folder contains primeng dependencies
  • import ToastModule into your angular module so that all components in the modules are avialable in your components
import {  ToastModule, MessageService, ButtonModule } from 'primeng';
@NgModule({
  imports:      [ ToastModule],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent ],
  providers:[MessageService]
})
export class AppModule { }

toast stackblitz example

Complete working examples for this article found in angular toast primeng example stacblitz

Similar Posts