sameera207 sameera207 - 27 days ago 11
TypeScript Question

Callback when a modal form closes

How can I call a method after I close a modal form in ionic2 (

v 2.1.7
) ? Following is my workflow


  • user loads a page (page A)

  • then click on a button to open a modal form (page B)

  • add some details (this will update a service)

  • close the modal form (page B)

  • Now I want to add a callback to page A and read the new value from
    the service



This is what I've done

#page A
let modal = this.modalCtrl.create(NewListPage);
modal.present();
getValueFromService()

#page B
updateService()
this.viewCtrl.dismiss();


Currently what happens is, once the program hits
modal.present();
, its not waiting for the
Page B
to close before its going to
getValueFromService()
, due to this, the newly updated value cannot be read once I close the modal form.

any help would be much appreciated

cheers

Answer

You can use onDidDismiss (doc) like this:

 // Page A
 presentModal() {
   let modal = this.modalCtrl.create(NewListPage);

   modal.onDidDismiss(() => {
     // This is going to be executed when the modal is closed, so
     // you can read the value from the service here
     getValueFromService();
   });

   modal.present();
 }

And then like you said

// Page B
updateService();
this.viewCtrl.dismiss();

Please also notice that you can send data between the Page A and the Page B, so maybe you can even avoid using a service (if you're doing it just for sending the data back and forth) and just send the data like this:

 // Page A
 presentModal() {
   let modal = this.modalCtrl.create(NewListPage);

   modal.onDidDismiss(dataFromModal => {
     // You can use the data here
     console.log(dataFromModal.foo);
   });

   modal.present();
 }

And in page B

// Page B
// Instead of calling the service, you can send the data to the caller
let data = { 'foo': 'bar' };
this.viewCtrl.dismiss(data);