sandrina-p
sandrina-p

Reputation: 4160

ionic2 - create function only when user clicks "close" inside Toast

I created a toast with ionic2 (+ angular2 with javascript, not typescript), where the user removes a item from the list.

So far so good, now I want to add a button Undo (replace Close by Undo) inside the toast to put it back on list and at the same time Dismiss the toast.

My code so far:

archiveItem(item) {
    let toast = Toast.create({
        message: 'Item archived.',
        duration: 2000,
        showCloseButton: true,
        closeButtonText: 'Undo',
        dismissOnPageChange: true,
    });

    var index = this.items.indexOf(item);
    this.items.splice(index, 1); //remove the item


    toast.onDismiss(() => {
        console.log('Dismissed toast');
        this.items.splice(index, 0, item); //put back the item on right place
    });


    this.nav.present(toast);
}

When I click Undo, the item returns to the list, the problem is that if I don't click it, it goes back to the list as well.

I suppose I need to create another function to the Undo, but I don't know how to do that, and Ionic2 DOCS don't talk about it...

Thank you :)

Upvotes: 5

Views: 3610

Answers (2)

Dorian Spc Lovera
Dorian Spc Lovera

Reputation: 1

In Ionic 4 this is what worked for me:

    toast.onDidDismiss().then(val => {
      if (val.role== "cancel") {
       //Action
     }
  });

Upvotes: 0

Manu Valdés
Manu Valdés

Reputation: 2371

Edit:

Try this:

 toast.onDismiss((data, role) => {    
        console.log('Dismissed toast');
        if (role== "close") {
           this.items.splice(index, 0, item); //put back the item on right place
        }
    });

edit: renamed parameters for clarity

Upvotes: 13

Related Questions