How to Show and Customize Toast Notification in Ionic 7 App

Last Updated on by in Ionic

It has come to my attention that many of us face problems implementing Toast notifications or messages in the Ionic application.

So, today i will eradicate this problem by showing you the facile way of implementing Toasts UI components in the Ionic 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 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 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:

sudo 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

Run the below command to add the native core package.

npm install @ionic-native/core --legacy-peer-deps

Disable Strict Type Errors

To avoid TypeScript compiling issues, we just need to open tsconfig.json file:

First, set below property under “compilerOptions” property.

"compilerOptions": {
    "strictPropertyInitialization": false,
    "skipLibCheck": true
    ...
}

Secondly, add given props under “angularCompilerOptions”.

"angularCompilerOptions": {
    "strictTemplates": false,
    ...
}

Import ToastController in Ionic

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

To show you the Ionic 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 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 --legacy-peer-deps

Run the command to test the application.

ionic serve -l

Ionic 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.

Name Description
--background Background of the toast
--border-color Border color of the toast
--border-radius Border radius of the toast
--border-style Border style of the toast
--border-width Border width of the toast
--box-shadow Box shadow of the toast
--button-color Color of the button text
--color Color of the toast text
--end Position from the right if direction is left-to-right, and from the left if direction is right-to-left
--height Height of the toast
--max-height Maximum height of the toast
--max-width Maximum width of the toast
--min-height Minimum height of the toast
--min-width Minimum width of the toast
--start Position from the left if direction is left-to-right, and from the right if direction is right-to-left
--white-space White space of the toast message
--width Width of the toast

Summary

Ultimately, we have seen how to create Toast notification in Ionic. 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.