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.

1
  • Sending data from modal to component is not support in ionic 2. I use some hidden part in my page instead. Commented Jan 7, 2017 at 13:52

2 Answers 2

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

1
  • ViewController was removed in v4, use ModalController for dismissing instead.
    – Clint
    Commented Jan 8, 2020 at 17:21
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 } 
  );
}
1
  • it says "onDismiss" is not a function
    – Fay007
    Commented Nov 22, 2019 at 16:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.