Customize the action button of a toast in Ionic 1 Framework

The problem

You are creating your hybrid app and when your user deletes an item from the cart you want to show a toast with the confirmation message and a button to undo the action, but in the documentation there's no way to customize the callback, so how to do this?

My boring problem and the way to solve it

This was, more or less, my case. After a lot of searches, and a nice headache - maybe it was only the air conditioner - when I decided to renounce finally the answer!

Things to know about how to solve it:

  1. The ToastController class has a dismiss method;

  2. The dismiss method callback has two arguments, and not one.

Why this is so important? Because without the second parameter, which specifies the motivation of the dismiss: the callback is invoked when the toast disappears automatically after the specified time or when the user clicks the button, there was no way to understand when was the button and when the timeout was.

But stop talking and start coding.

Code!

First of all, include ToastController in your .ts page:

import { ToastController } from 'ionic-angular';

And include it in your constructor:

constructor(public toastCtrl: ToastController) {

Now we can create the toast, like the documentation, customize also the close button message.

// Create a toast
let toast = this.toastCtrl.create({
    message: 'Item removed from the cart',
    duration: 3000,
    showCloseButton: true,
    closeButtonText: 'Undo',
});

I was talking about the dismiss callback, so let's write it.

// Handle "undo" action
toast.onDidDismiss((data, role) => {
    //
});

As you can see, there's a second parameter called role and with it, we can execute our code only when the user hits the button.

// Handle "undo" action
toast.onDidDismiss((data, role) => {
    if (role == 'close') {
        yourRecoveringMethod();
    }
});

And, finally, let's show the toast with toast.present();. The final code will look like this:

// Create a toast
let toast = this.toastCtrl.create({
    message: 'Item removed from the cart',
    duration: 3000,
    showCloseButton: true,
    closeButtonText: 'Undo',
});

// Handle "undo" action
toast.onDidDismiss((data, role) => {
    if (role == 'close') {
        yourRecoveringMethod();
    }
});

toast.present();

This was so simple, why not include it in the documentation? This will be a mystery.