22

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.

TheUnreal
  • 23,434
  • 46
  • 157
  • 277

2 Answers2

53

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

johnny 5
  • 19,893
  • 50
  • 121
  • 195
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
4

This is a clear example of getting data from modals in ionic. You need to add a handler for modal’s onDismiss() and then return the data from the modal itself by passing the data to the ViewController’s dismiss() method:

// myPage.ts
// Passing data to the modal:
let modal = Modal.create(myModal, { data: [...] });

// Getting data from the modal:
modal.onDismiss(data => {
  console.log('MODAL DATA', data);
 });

this.nav.present(modal);

on the modal page

// myModal.ts
constructor(private navParams: NavParams, private viewCtrl: ViewController) {
// Getting data from the page:
  var dataFromPage = navParams.get('data');
}

dismiss() {
// Returning data from the modal:
  this.viewCtrl.dismiss(
      // Whatever should be returned, e.g. a variable name:
      // { name : this.name } 
  );
}
Felix Runye
  • 2,135
  • 1
  • 20
  • 20