TheUnreal
TheUnreal

Reputation: 24472

Ionic 2 - Get data back from modal

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:

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

Upvotes: 22

Views: 22042

Answers (2)

Felix Runye
Felix Runye

Reputation: 2521

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

Upvotes: 4

Suraj Rao
Suraj Rao

Reputation: 29614

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

Upvotes: 53

Related Questions