Ionic 5 Toast Tutorial: How to Show and Customize Toast Notification in Ionic

Last updated on by Digamber

It has come to my attention that many of us face problems implementing Toast notifications or messages in the Ionic 5 application. So, today i will eradicate this problem by showing you the facile way of implementing Toasts UI components in the Ionic 5 Angular application.

A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive. Toasts automatically disappear after a timeout.
– android

While browsing on the web and mobile applications, a little box manifests on the screen with a message. This is called Toast Notification, and it is beneficial for conveying an important message to the user. It grabs the user’s attention and displays success, error, or other messages.

This tutorial walks you through on implementing Toast UI to Ionic 5 and display notification in the Ionic application. Well, the good thing is we will create this functionality without using any third-party plugin.

Our primary focus will be on integrating and customizing the Ionic 5 Toast UI component using its custom properties, including how to change the position of toast, dismiss the toast, create the toast, and style the toast.

Install Ionic Application

First, you need to install Ionic CLI using the following command:

npm install -g @ionic/cli

Now, make the locus of Ionic application on your machine.

ionic start ionic-toasts-notification blank --type=angular

Get into the project folder:

cd ionic-toasts-notification=angular

Import ToastController in Ionic

We need to import the ToastController class in Ionic application from ‘@ionic/angular’ package.

To show you the Ionic 5 Toast example, i am using the default Home component. So, add the following code in the home.page.ts file.

import { Component } from '@angular/core';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  constructor(public toastController: ToastController) {}

}

Create Toast in Ionic

The ToastController offers the create() method, which lets you create a Toast UI. Programmatically it returns a promise and then(), and we need to access the present() method to display the Toast.

Add the code in home.page.ts file:

import { Component } from '@angular/core';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  constructor(public toastController: ToastController) {}

  displayToast() {
    this.toastController.create({
      header: 'Welcome!',
      message: 'John!',
      position: 'top',
      cssClass: 'toast-custom-class',
      buttons: [
        {
          side: 'end',
          icon: 'person',
          handler: () => {
            console.log('');
          }
        }, {
          side: 'end',
          text: 'Close',
          role: 'cancel',
          handler: () => {
            console.log('');
          }
        }
      ]
    }).then((toast) => {
      toast.present();
    });
  }  

}

You can check out the complete properties of the create method to customize the Toast component.

Define the Ionic button with custom method that will open the Toast UI on click event, also add the code in home.page.html file:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Ionic 5 Toast Notification Example
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <div id="container">
    <ion-button color="danger" (click)="displayToast()">Open Toast</ion-button>
  </div>
</ion-content>

Next, install the Ionic lab plugin with --save-dev development dependencies attribute.

npm install --save-dev @ionic/lab

Run the command to test the application.

ionic serve -l

Ionic 5 Toast Tutorial

Stop Multiple Toast Piling in Ionic

We have implemented the toast in the ionic application. But if you have noticed, a pile of toast implied in one place. To solve the multiple toast overlapping issue, we will define the try{…} method, then call the dismiss() method within the finally() method. It will prevent the numerous toasts from opening.

import { Component } from '@angular/core';
import { ToastController } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  constructor(public toastController: ToastController) {}

  displayToast() {
    
    // Stop multiple toasts 
    try {
      this.toastController.dismiss().then(() => {
      }).catch(() => {
      }).finally(() => {
        console.log('Closed')
      });
    } catch(e) {}
    
    this.toastController.create({
      header: 'Welcome!',
      message: 'John!',
      position: 'top',
      cssClass: 'toast-custom-class',
      buttons: [
        {
          side: 'end',
          icon: 'person',
          handler: () => {
            console.log('');
          }
        }, {
          side: 'end',
          text: 'Close',
          role: 'cancel',
          handler: () => {
            console.log('');
          }
        }
      ]
    }).then((toast) => {
      toast.present();
    });
  }

}

Add Custom Styling in Ionic Toast

We are now adding the custom styling in Ionic Toast; we have already defined the custom class within the create() method. Now, we will use it and add some custom styling to beautify it. Head over to global.scss file and add the below style.

.toast-custom-class {
    --color:#ffffff;
    --border-color:#000000;
    --border-radius:3px;
    --border-style:solid;
    --border-width:3px;    
    --background:#1833FF;
    --button-color:#ffffff;
}

Add Custom Styling in Ionic Toast

Here are the properties that you can use to style the toast.

NameDescription
--backgroundBackground of the toast
--border-colorBorder color of the toast
--border-radiusBorder radius of the toast
--border-styleBorder style of the toast
--border-widthBorder width of the toast
--box-shadowBox shadow of the toast
--button-colorColor of the button text
--colorColor of the toast text
--endPosition from the right if direction is left-to-right, and from the left if direction is right-to-left
--heightHeight of the toast
--max-heightMaximum height of the toast
--max-widthMaximum width of the toast
--min-heightMinimum height of the toast
--min-widthMinimum width of the toast
--startPosition from the left if direction is left-to-right, and from the right if direction is right-to-left
--white-spaceWhite space of the toast message
--widthWidth of the toast

Summary

Ultimately, we have seen how to create Toast notification in Ionic 5. We saw how to customize the toast UI using a custom CSS class using the create() function. Also, We learned the easy way to stop opening multiple toasts at the same time.

If you loved this tutorial, then do share it with others.