Ionic Toast example from scratch – Step by step details tutorial

Ionic toast component can be used to display notification information for a short period of time by using ToastController. Ionic comes with a number of components, including modals, popups, and cards.  Ionic toast is a subtle notification commonly used in modern applications.

We’ll be exploring how to implement ionic toast by customizing Ionic toast CSS, message, toast color, and toast position. Keeping one toast code for the whole application using toast service is best the practice of code reusability.

Prerequisites:
To create and run an Ionic project, We need Node js and Ionic CLI already install in our system, if not then check how to install Node js and Ionic in Ubuntu. Ionic CLI allows us to create an Ionic project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install the Ionic CLI, open a terminal, and run the following command:

npm install -g @ionic/cli

Setuping up an Ionic toast project

With the release of ionic version 4, the Ionic framework no longer limited to angular, we can create the ionic projects in different front-end frameworks like Angular, Vue, and React. Let first create a blank Ionic Angular project. The Ionic framework makes it easy to implement Ionic toast on your apps.

ionic start toastExample blank

What is an ionic toast controller ?

From the ionic official definition of toast: “A Toast is a subtle notification commonly used in modern applications. It can be used to provide feedback about an operation or to display a system message.” . We have seen in mobile applications, short-duration notifications on the application screen. Ionic toast is commonly used to provide feedback, error/ other messages about a particular task’s status, or simply display a short message on top of the app’s content. Ionic toast messages can be displayed either on the top of the screen, middle, and on the bottom area.

How to implment Ionic toast controller ?

In our first Ionic toast example, we are using the toast controller directly on our page. In the second example, we’ll create a toast service. We are displaying an ionic toast controller to display toast messages at different events as follows.

  • Display Toast message when the mouse cursor comes over an image.
  • Display ToastController message over different positions of application like the top, middle, and bottom.
  • Display different ToastController messages when all form fields are filled or not filled.
Ionic toast example

Here’s a quick screenshot of what we’ll be building.

We need to edit the following code in the home.page.html template, here we have added a few buttons to shows different toast duration, and positions.

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>
      Ionic Toast Controller Example
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-card>
    <img id="imgSection" src="assets/images/toast.png">
  </ion-card>

  <ion-button expand="full" (click)="showToast('top')">
    Show Toast Top Position</ion-button>
  <ion-button expand="full" (click)="showToast('bottom')">
   Show Toast Bottom Position</ion-button>
  <ion-button expand="full" (click)="showLongToast()">Show Long Toast</ion-button>
  <ion-button expand="full" (click)="showToastWithCloseButton()">
    Show Toast WITH Close Button
  </ion-button>
 
  <ion-list>
    <ion-item>
      <ion-label fixed>Name</ion-label>
      <ion-input type="text" name="ngModel" [(ngModel)]="name"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Birthday</ion-label>
      <ion-datetime displayFormat="MM/DD/YYYY" [(ngModel)]="birthday"></ion-datetime>
    </ion-item>
    <ion-button color="success" expand="full" (click)="save()">Save</ion-button>
  </ion-list>
</ion-content>

Now we need to import the ionic toast controller from @ionic/angular in the home.page.ts file. An instance of Toast Controller has to be injected into our constructor as the property.

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 {
  imgToast: HTMLElement;
  name: string;
  birthday: string;

  constructor(private toastController: ToastController) {
    this.birthday = new Date().toISOString();
  }

  ngOnInit() {
    this.imgToast = document.getElementById('imgSection');
    this.imgToast.addEventListener('mousemove', ev => {
      this.showToastOnImage();
    });
  }

  async showToastOnImage() {
    const toast = await this.toastController.create({
      message: 'On MouseOver event on an image',
      duration: 2000,
      position: 'middle',
      color: 'danger'
    });
    toast.present();
  }

  async showToast(position: any) {
    const toast = await this.toastController.create({
      message: 'Mmmm, buttered toast',
      duration: 1000,
      position,
      color: 'tertiary',
      cssClass: 'toast-1-css',
    });
    toast.present();
  }

  async showToastWithCloseButton() {
    const toast = await this.toastController.create({
      message: 'Your files were successfully saved',
      position: 'middle',
      cssClass: 'toast-2-css',
      buttons: [
        {
          side: 'start',
          icon: 'happy',
          handler: () => {
            console.log('Favorite clicked');
          }
        }, {
          side: 'end',
          icon: 'close',
          text: 'Close',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    toast.present();
  }

  async showLongToast() {
    const toast = await this.toastController.create({
      message: 'Example of showing long toast',
      duration: 4000,
      position: 'top',
      color: 'secondary',
    });
    toast.present();
  }

  async save() {
    if (this.name && this.birthday) {
      const toast = await this.toastController.create({
        message: 'User profile was saved successfully',
        position: 'middle',
        color: 'success',
        duration: 3000
      });
      toast.present();
    } else {
      const toast = await this.toastController.create({
        message: 'User profile field is not filled',
        position: 'middle',
        color: 'danger',
        duration: 3000
      });
      toast.present();
    }
  }
}
Ionic toast message over image

We have applied toast in different situations like mouse move over an image and different toast messages when form fields are fills or without fill. Toast can have a button-like close or cancel or icon using the ToastButton option. We can have the following value to ToastButton options.

export interface ToastButton {
  text?: string;                      // Button name
  icon?: string;                     // Ionic icon name
  side?: 'start' | 'end';           // Icon position  
  role?: 'cancel' | string;
  cssClass?: string | string[];
  handler?: () => boolean | void | Promise<boolean | void>;
}

What are Ionic toast controller properties ?

When creating a new ionic toast notification using the method create() from the toast object, we can pass an object to configure the toast notification. The following configuration properties are supported by ToastController.

Properties Description
message Message to display.
duration Number of milliseconds before the toast is dismissed.
position Position to show the toast; possible values are top, middle, and bottom.
showCloseButton Whether to show a button to close the toast.
closeButtonText Text of the close button.
dismissOnPageChange Whether to dismiss the toast when navigating to a different page.
color To have different background color to toast, we have color from ionic variables.scss

In our example we have used toast option like message, color, position and buttons also.

How to change Ionic toast color. ?

We can apply ionic toast with different colors to our ionic toast by using the color properties of toast options. We can select different colors available from the variable.scss. If you want a different color, which is not available in variable.scss, then you can add a new color in varaible.scss.

In the real application scenario is an example below, we have used toast controlled to display notification messages we user profile data is an update to the Firebase database. You can keep API calls to firebase in services.

editProfileInfo() {
  this.db.list('/profiles/').update(this.navParams.get('userId'), this.profileRef).then(data => {
    const toast = await this.toastController({
      message: 'User Profile Add successful',
      duration: 3000,
      position: 'top'
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  });
}

How to design Ionic Toast component using custom CSS properties.?

We can apply style on Ionic toast by using cssClass properties of Toast options. In our case, we have a different pink background and rounded border on one of our toast. This can achieve by giving a name to cssClass property in the Toast option. We can’t used this toast cssClass directly in our page, as it is global we need to add this style properties in global.scss. For our example we have used toast-2-css in one of our toast options in home.page.ts file.

  cssClass: 'toast-2-css',

As Ionic toast style need to apply in global.scss and we need to add following style at end of global.scss

.toast-2-css {
    --background: #eb445a;
    --border-radius:2px;  
}

Ionic has lots of custom CSS for styling our Ionic toast design. Here is a list of all custom CSS we can apply on ionic toast.

Name Description
–backgroundBackground of the toast
–border-colorBorder color of the toast
–border-radiusBorder radius of the toast
–border-styleBorder style of the toast
–border-widthThe border 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 the direction is left-to-right, and from the left, if the 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 the direction is left-to-right, and from the right, if the direction is right-to-left
–white-spaceWhite space of the toast message
–widthWidth of the toast
Ionic custom CSS for Ionic toast Controller

What are Ionic toast methods ?

Ionic toast components have different methods which we can used on our toast Object like create and dismiss methods and more. I have listed all methods avaliable on ionic toast controller.

Methods NameDescription
createMethod to create an Toast message
dismissDismiss the toast overlay after it has been presented.Its optional.
onDidDismissReturns a promise that resolves when the toast did dismiss.
onWillDismissReturns a promise that resolves when the toast will dismiss.
presentPresent the toast overlay after it has been created.
Ionic toast method

We have used both create and present methods in our previous example.

How to dismiss toast in Ionic?

In the previous example, we didn’t used dismiss method on ionic toast and there are different ways of calling dismiss methods. First by using the duration property of the toast object and we need to specify the time setting in millisecond in the duration property. The toast notification can be dismissed automatically after a specific amount of time it expires.

The second approach is to use the cancel button on the toast object by setting the button role to cancel and clicking on it will dismiss toast. We can also use dismiss method directly on the toast object and will call on after toast is created. To dismiss all previous toast objects, and call new toast message. We can call the toast controller object from the constructor with dismiss methods. On this dismiss method we can call promise to check if any error or when promised is complete we can call our custom method to invoke a new toast.

toast.dismiss();
Or 
this.toastController.dismiss().then(() => {})
   .catch(() => {})
   .finally(() => {
      // Call to show toast method
});

Ionic toast events

Like toast methods, we have an Ionic toast event on our toast object. We can use this event to check different activities on our toast object. Like if toast is dismissed or not, these are hooks we can use on toast objects. Here we have listed all events on the toast controller.

NameDescription
ionToastDidDismissEmitted after the toast has dismissed.
ionToastDidPresentEmitted after the toast has presented.
ionToastWillDismissEmitted before the toast has dismissed.
ionToastWillPresentEmitted before the toast has presented.

We’ll demonstrate one example how to used above evens on our ionic toast object.

  async showLongToast() {
    const toast = await this.toastController.create({
      message: 'Example of showing long toast',
      duration: 4000,
      position: 'top',
      color: 'secondary',
    });
    toast.present();

    toast.onDidDismiss().then(() => {
      console.log('Dismissed toast');
    });
  }

How to implment Ionic toast using service ?

In application, Ionic Toast can apply at different pages | components. Is a good practice to create a common service where we add all our common code. In our case, we will create an Ionic toast service called common and this will helps us to manage our code easier and reduce common code in an application. This is a good programming practice of keeping all reusable code in a single file.

Ionic toast service

Lets first generate common service in services folder, in this common.service.ts we”ll add all common code like toast, alert and modal etc.

ionic generate service services/common

Edit common.service.ts file, showToast method can accept two-argument, first is color for toast background and the second argument is a message we want to display in a toast. We need to import ToastController from ionic/angular and you can remove our previous example of adding toast code on a single page.

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

@Injectable({ providedIn: 'root' })
export class CommonService {

  constructor(private toastCtrl: ToastController) { }

  async showToast(color: string, msg: string) {
    const toast = await this.toastCtrl.create({
      message: msg,
      duration: 2000,
      color,
      position: 'middle'
    });
    toast.present();
  }
}

Importing our reusability toast controller code.

Now we can share Ionic toast service code everywhere in our application. You can add it to pages, components, or other services also. Let’s used the common toast service in home.ts pages as.

import { Component, OnInit } from '@angular/core';
import { CommonService } from '../services/common.service';

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

  constructor(private common: CommonService) { }

  toastMsgFromService(color: string, msg: string) {
    this.common.showToast(color, msg);
  }
}

In home.page template we have two button to display different toast message and color using Ionic toast service.

<ion-header>
  <ion-toolbar color="primary">
    <ion-title>
      Ionic Toast Service Example
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-button expand="full" color="success" (click)="toastMsgFromService('success', 'Toast from Common provider - success')">Success
    Toast From Service</ion-button>
  <ion-button expand="full" color="warning" (click)="toastMsgFromService('danger', 'Toast from Common provider - failure')">Fail Toast
    From Service</ion-button>
</ion-content>

Summary
We have explored how to used ionic toast in detail. By using toast directly on the page and ionic toast service to share the same toast code among different pages. Is recommended to used a reusable code-like service to share the same toast code throughout the application.

Related posts

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top