26

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.

MLynch
  • 425
  • 1
  • 4
  • 12
  • Ionic 4's documentation need much more work before it is good enough to start messing with it. I tried it for a week and gave up after finding the alerters examples incredibly non intuitive to initialize and use. – Anjil Dhamala Oct 12 '18 at 19:28

2 Answers2

92

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!

starball
  • 20,030
  • 7
  • 43
  • 238
Roman
  • 3,011
  • 2
  • 20
  • 30
  • 3
    You are a saint. This is exactly what I needed - I hadn't thought to use ".then()" to handle the returned data. Thank you so much. – MLynch Oct 12 '18 at 21:18
  • Do you know how to differentiate when a component was opened my a modal controller or a router navigation in order to dismiss the component according to it? – ingkevin Apr 17 '19 at 14:31
  • I would just pass different componentProps to the modal – Roman Apr 18 '19 at 14:31
  • 2
    Your way is working! But in the doc its written like this `const modal = await modalController.create({...}); const { data } = await modal.onDidDismiss(); console.log(data);` But when I used the same its not working, why? – Ankur Shah May 26 '19 at 13:19
  • What's up with the first code snipped being empty? Bad edit? – GoForth Dec 26 '22 at 02:06
5

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);
})
Kirill Rakhman
  • 42,195
  • 18
  • 124
  • 148
Ion Scorobogaci
  • 147
  • 2
  • 5