Ionic 2 - Get data back from modal

TheUnreal picture TheUnreal · Jan 7, 2017 · Viewed 21.3k times · Source

I have a component which is my main interface. Inside this component, clicking a button opens ionic 2 modal which allows to choose items.

My modal page (itemsPage):

..list of items here

    <button ion-button [disabled]="!MY_TURN || !selectedItem || !selectedItem.quantity"
       (click)="useItem(selectedItem)">
        <span>Choose item {{selectedItem?.name}}</span>
      </button>

useItem() should:

  • Send item data to my main interface component
  • Close the modal
  • Execute a method in my main interface

How I can perform such actions? Couldn't find any documentation about communicating between modal and component in Ionic 2.

Answer

Suraj Rao picture Suraj Rao · Jan 7, 2017

It is simply a matter of using parameters in viewController.

In your main interface component,

let chooseModal = this.modalCtrl.create(itemsPage);
  chooseModal.onDidDismiss(data => {
     console.log(data);
});
chooseModal.present();

In your modal page,

useItem(item) {   
  this.viewCtrl.dismiss(item);
}

Modal Controller link here