Pages

How to Implement ModalController in Ionic 2 and Ionic 3.

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 NavControllers 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 and Paste the below given code to your myhomepage.ts file.

myhomepage.ts


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

    }

Code and Paste the below given code to your details.ts file.

details.ts


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

    }


vinay kumar

Founder of Gowriter.Blogspot.com, Tech Enthusiast, Normal type of Person with passion toward's work.

No comments: