Wednesday 8 July 2020

Passing Data from Ionic PopoverController

Since Ionic version 5, Events is no longer supported and will give compilation error. I have posted Using Popover Controller in Ionic but there's a proper way to pass data back from the popover controller to the caller.

We should leverage onDidDismiss() function in the caller component and passing the data as an argument of dismiss() function in the popover.

Caller component create and show popover:
async showCalculateWeeklyRent(ev) {
 const popover = await this.popoverCtrl.create({
  component: CalculateRentComponent, // the popover component that we created
  event: ev,
  componentProps: { 
     // data to be passed
     . . .
  },
  cssClass: 'popoverClass',
 });

 // get data returned from the popover
 popover.onDidDismiss().then(returnedValue => {
  if (returnedValue.data) {   // need to access the 'data' property to get the returned value
   this.model.weeklyRent = returnedValue.data;
   this.calculateYearlyRent();
  }
 });

 return await popover.present();
}
Note that we need to use the data property to get the value.

Then on the popover component, we can simply pass an argument when closing it:
. . .
     
closeAndReturnData() {
    // pass data to caller
    this.popoverCtrl.dismiss(this.shouldBeWeeklyRent);
}

closePopOver() {
    // simply close it
    this.popoverCtrl.dismiss();
}

. . .