Ionic 4 - Pass Data BACK from Modal

我们两清 提交于 2019-12-20 18:34:11

问题


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.


回答1:


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:

constructor(private modalController: ModalController){}

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();
  }

I hope this helps! If anything is unclear, just ask!




回答2:


Below code is working for me.

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();
  }



回答3:


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);
    })



回答4:


  //**to receive data from modal once the modal is closed** 
    dismiss() {
   this.viewCtrl.dismiss({id: this.id});//or this.viewCtrl.dismiss({id:24});

    }

   async openModal(brand) {
  const modal = await this.modalController.create({
  component: ViewBrandPage,
  componentProps: { name : brand.name, id : brand.id, sub : brand.sub_id }
  });
  // **data from modal once the modal is closed**
    modal.onDidDismiss()
    .then((data) => {
       const user = data.data.id;
      alert(user);
      console.log(user);
    });
   return await modal.present();
    }


来源:https://stackoverflow.com/questions/52785797/ionic-4-pass-data-back-from-modal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!