How to Implement Toast in Ionic

Ionic comes with a number of components, including modals, popups, and cards.  Ionic ToastController can be used to display information for the short period of time by using ToastController.  The toast is commonly used to provide feedback, error/ other messages about a particular task’s status or to simply display a short message on top of app’s content. The Toast message can be displayed either on the top of the screen, middle and on the bottom area.

The Ionic makes it easy to implement toast on your app’s. follow the below steps to implement toast in your ionic app.

Step 1: Create a project to implement ToastController

ionic start toastExample blank

Step 2: Import the ToastController and add ToastController code in Typescript

We have to import ToastController from ionic-angular and the instance of ToastController have to be into ou constructor as the property. In this example, we are using ToastController to display message on

  1. Display Toast message when the mouse cursor comes over image
  2. Display ToastController message over different position – ionic ToastController example code from ionic documentation.
  3. Display different ToastController message when all form fields are filled or not filled.

    ionic ToastController
    ionic ToastController

Add the following code in home.ts file

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

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  imgToast: HTMLElement;
  name: string;
  brithday: any;

  constructor(public toastCtrl: ToastController) {
    console.log("value of name : ", this.name);
    this.brithday = new Date().toISOString();
  }

  ngOnInit() {
    this.imgToast = document.getElementById('imgSection');
    this.imgToast.addEventListener('mousemove', ev => {
      let toast = this.toastCtrl.create({
        message: 'On MouseOver event on an image',
        duration: 2000,
        position: 'middle'
      });
      toast.present(toast);
    });
  }

  showToast(position: string) {
    let toast = this.toastCtrl.create({
      message: 'Mmmm, buttered toast',
      duration: 1000,
      position: position
    });
    toast.present(toast);
  }

  showToastWithCloseButton() {
    const toast = this.toastCtrl.create({
      message: 'Your files were successfully saved',
      showCloseButton: true,
      closeButtonText: 'Ok'
    });
    toast.present();
  }

  showLongToast() {
    let toast = this.toastCtrl.create({
      message: 'Example of showing long toast',
      duration: 4000,
    });
    toast.present();
  }

  save() {
    console.log("Name in save : ", this.name);
    console.log("Birthday in save : ", this.brithday);
    if(this.name != null && this.brithday != null){
      let toast = this.toastCtrl.create({
        message: 'User profile was saved successfully',
        position: 'bottom',
        duration: 3000
      });
      toast.present();
    }
    else {
      let toast = this.toastCtrl.create({
        message: 'User profile field is not filled',
        position: 'bottom',
        duration: 3000
      });
      toast.present();
    }

  }
}

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

  1. message – Message to display.
  2. duration – Number of milliseconds before the toast is dismissed.
  3. position – Position to show the toast; possible values are top, middle and bottom.
  4. showCloseButton – Whether to show a button to close the toast.
  5. closeButtonText – Text of the close button.
  6. dismissOnPageChange – Whether to dismiss the toast when navigating to a different page.

Step 3: We need to add following code in the home.html template 

<ion-header>
  <ion-navbar color="primary" text-center>
    <ion-title>
      Ionic Toast Example
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-card>
    <img id="imgSection" src="assets/imgs/toast.jpg">
  </ion-card>

  <button ion-button block (click)="showToast('top')">Show Toast Top Position</button>
  <button ion-button block (click)="showToast('bottom')">Show Toast Bottom Position</button>
  <button ion-button block (click)="showLongToast()">Show Long Toast</button>
  <button ion-button block (click)="showToastWithCloseButton()">Show Toast W/ Close Button</button>
  
  <ion-grid>
    <ion-item>
      <ion-label fixed>Name</ion-label>
      <ion-input class="right" 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" presentWith="min"></ion-datetime>
    </ion-item>
    <button ion-button color="secondary" block (click)="save()">Save</button>
  </ion-grid>

</ion-content>




In the example below, we have use toastController to display notification message we user profile data is an update to Firebase database.

  editProfileInfo(){
    this.db.list('/profiles/').update(this.navParams.get('userId'), this.profileRef).then( data => {
      let toast = this.toastCtrl.create({
        message: 'Additional User Profile Add successful',
        duration: 3000,
        position: 'top'
      });
    
      toast.onDidDismiss(() => {
        console.log('Dismissed toast');
      });
    
      toast.present();
    });