MLynch
MLynch

Reputation: 435

Ionic 4 - Pass Data BACK from Modal

I'm trying to create a modal window, pass it an array of objects, have a user select one object from that array, and then have my modal pass back the object they've selected.

I've tried using the Ionic 2 approach of modalName.onDidDismiss(data=> …) as explained here, but apparently Ionic 4 changed "onDidDismiss" to not accept any values passed back to it.

So I'm at a loss for how to send data from my Modal window back to the page that called it.

Upvotes: 27

Views: 47600

Answers (2)

Roman
Roman

Reputation: 3149

Some days ago I had the same problem and here's my solution:

I guess, you already have a component which contains the actual modal. name UserModalComponent

Your UserModalComponent should get the ModalController injected:

Next step is to pass the selected user back:

selectUser(user: User):void {
  this.modalController.dismiss(user);
}

In your component in which you want to call the modal and get the user back, you also have to inject the ModalController as above and additionally, you need this method:

 async openUserModal() {
    const modal = await this.modalCtrl.create({
      component: UserModalComponent,
      componentProps: { users: this.users },
    });

    modal.onDidDismiss()
      .then((data) => {
        const user = data['data']; // Here's your selected user!
    });

    return await modal.present();
  }

If anything is unclear, just ask!

Upvotes: 94

Ion Scorobogaci
Ion Scorobogaci

Reputation: 165

This is how you get data back from modal in Ionic 4 :

contactsModal.onDidDismiss().then(data => {
    console.log('data came back from modal');
    console.log(data);
})

Upvotes: 5

Related Questions