Monday, 22 May 2017

How to Implement ModalController and pass data to modal.

A Modal is similar to page, but it goes over the app's current page and is displayed as a popup page. Modal is generally used to select an item from a group or to make a choice.
A modal uses the NavController to present itself . It is added to the stack similar to how NavController's push works.
A modal is "presented" by calling present method.

ionicModal.present();

after the modal has been presented, The modal can later be closed or "dismissed" from within the component instance by using the ViewController's dismiss method.

Data can be passed to a new modal through create method as the second argument.

let ionicModal = this.modalCtrl.create(ionicModal, { Id: 5 });

The data that is passed through create method, can then be accessed from the opened page/modal by using NavParams.

this.params.get('Id');

Once the Modal work is done with, when the modal is dismissed, we can send back or pass required data from modal to previous page by calling the dismiss method.

this.viewCtrl.dismiss(data)

Now, that the modal is closed, the data is passed from modal is received at onDidDismiss method.

ionicModal.onDidDismiss(data => {
console.log(data);
});

Code to implement ModalController and pass data to modal to and forth


 

MyHomePage ts file.





import { Component } from '@angular/core';
import { ModalController, ViewController } from 'ionic-angular';
import { NavController, NavParams } from 'ionic-angular';
import { DetailsPage } from '../details/details'
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
UserId:any;
UserName:any
constructor(public modalCtrl: ModalController,public params: NavParams) {
this.UserId = this.params.get('id');
this.UserName = this.params.get('name');
}

presentModal() {
let MyNewModal = this.modalCtrl.create(DetailsPage , { name: "kumar"});
MyNewModal.onDidDismiss(data => {
console.log(data);
});
MyNewModal.present();
}

}


details.ts file.



import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { ModalController, ViewController } from 'ionic-angular';

@Component({
selector: 'page-details',
templateUrl: 'details.html'
})
export class DetailsPage {

constructor(public viewCtrl: ViewController) {

}

dismiss() {
let data = { 'name':'kumar','id':'12345' };
this.viewCtrl.dismiss(data);
}

}

1 comment: