Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 2 - Get data back from modal

Tags:

ionic2

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.

like image 858
TheUnreal Avatar asked Jan 07 '17 12:01

TheUnreal


People also ask

How do I use pop in Ionic?

Confirm Popup OptionsThe subtitle of the popup. The CSS class name of the popup. The text for the Cancel button. The Ionic button type of the Cancel button.

How do I use modal controller in Ionic 4?

How to receive data from a page to modal in Ionic 4. If you want to receive data in the modal page, then you must use the NavParams class. import { NavParams } from '@ionic/angular'; Create the object reference for the NavParams class using the constructor in the view-player.


2 Answers

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

like image 58
Suraj Rao Avatar answered Oct 01 '22 12:10

Suraj Rao


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 } 
  );
}
like image 21
Felix Runye Avatar answered Oct 01 '22 12:10

Felix Runye