Ionic 5|4 How to Use Ionic Modal Popovers and Pass Data and Receive Response

In this post, we will discuss how to add Modal popups in Ionic applications built in Angular framework. We’ll also learn how to pass data from the parent component to a Modal and send back data from Modals to the parent page.

Modals are popup containers which are opened on top of the content. It is a container which floats over the page content and doesn’t occupy additional space. The Modal popup components are preferred to provide additional features or do extra actions on a page. We can create a page to act like a Modal with the only difference is these are loaded on above of the current page.

Here we will create a new Ionic Angular application and implement Modal component to discuss data communication.

Also Check: Ionic 3 Modal Popup Tutorial 

We can pass data to a Modal and also receive back response sent from the Modal component. We will discuss these in the example below.

Let’s get started!

These are the steps we are going to follow during this tutorial

1) Update @ionic/cli package

2) Create a new Ionic application

3) Create a MyModal page acting as a modal

4) Update MyModal page template and class

5) Update HomePage template and class

6) Import MyPage Module in the Home Module

7) Run the application to see it working!

#1 Update to the latest version

Make sure you have the latest version of @ionic/cli package installed. You can update it by running below command in the terminal window.

$ npm install -g @ionic/cli

The current version of @ionic/cli is version 6.6.0

 

 

#2 Create new Ionic App

Now create a new Ionic application using Angular framework using --type=angular option with starter blank template. Run the following command in the terminal to create a new application.

$ ionic start ionic-modal-demo blank --type=angular

move to the application folder

$ cd ionic-modal-demo

then open application folder in Visual Studio Code in installed by running

$ code .

 

#3 Create Modal Page

Now, we'll create a new page which will act as a component for Modal. This page will be shown as a Modal. Run the following generate command to create a new page with MyModalPage component in modals page.

$ ionic generate page modals/my-modal

Above command will create a new page in modals folder as shown below:

 

#4 Update Modal Page

After creating the MyModal page, let's update its template and component class files.

Update the my-modal.page.html file with following HTML template

<!-- my-modal.page.html -->
<ion-header>
  <ion-toolbar color="danger">
    <ion-title>my-modal</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">

  <ion-grid>
    <ion-row>
      <ion-col text-center>
        ID : {{modelId}}
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col text-center>
        <ion-button (click)="closeModal()">Close Modal</ion-button>
      </ion-col>
    </ion-row>
  </ion-grid>

</ion-content>

Here we are just displaying the value passed from Home page in the modelId variable in a ion-grid. The closeModal() method is programmatically closing the Modal.

Next, update the my-modal.page.ts class file with below code

// my-modal.page.ts
import { Component, OnInit } from '@angular/core';
import { 
ModalController, 
NavParams 
} from '@ionic/angular';

@Component({
  selector: 'app-my-modal',
  templateUrl: './my-modal.page.html',
  styleUrls: ['./my-modal.page.scss'],
})
export class MyModalPage implements OnInit {


  modalTitle: string;
  modelId: number;

  constructor(
    private modalController: ModalController,
    private navParams: NavParams
  ) { }

  ngOnInit() {
    console.table(this.navParams);
    this.modelId = this.navParams.data.paramID;
    this.modalTitle = this.navParams.data.paramTitle;
  }

  async closeModal() {
    const onClosedData: string = "Wrapped Up!";
    await this.modalController.dismiss(onClosedData);
  }

}

let's see what's happening inside this code

ModalController: This class provides the dismiss() method which can pass data to parent page from this modal is opened.

NavParams: This class helps in fetching the data passed in create() method from parent page from where this Modal is opened.

 

#5 Open Modal from Home Page

We'll open Modal( MyModalPage ) from the Home page which is created by default in the blank template app. You can call from any page in your application.

To open the Modal, we need to import the ModalController class from @ionic/angular module. Now add this module in the class constructor method.

// home.page.ts
import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(
    public modalController: ModalController
  ) { }

}

Next, we will call the create() method available in the ModalController to open a modal by passing component name in the option object

  async openModal() {
    const modal = await this.modalController.create({
      component: MyModalPage,
      componentProps: {
        "paramID": 123,
        "paramTitle": "Test Title"
      }
    });

    modal.onDidDismiss().then((dataReturned) => {
      if (dataReturned !== null) {
        this.dataReturned = dataReturned.data;
        //alert('Modal Sent Data :'+ dataReturned);
      }
    });

    return await modal.present();
  }

Finally, the home.page.ts file will look like this:

// home.page.ts
import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { MyModalPage } from '../modals/my-modal/my-modal.page';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  dataReturned: any;

  constructor(
    public modalController: ModalController
  ) { }

  async openModal() {
    const modal = await this.modalController.create({
      component: MyModalPage,
      componentProps: {
        "paramID": 123,
        "paramTitle": "Test Title"
      }
    });

    modal.onDidDismiss().then((dataReturned) => {
      if (dataReturned !== null) {
        this.dataReturned = dataReturned.data;
        //alert('Modal Sent Data :'+ dataReturned);
      }
    });

    return await modal.present();
  }

}

Here we are passing data to the Modal using componentProps property of create() method object.

 

Update Home Page template in the home.page.html file with a button to call the openModal() method

<!-- home.page.html -->
<ion-header [translucent]="true">
  <ion-toolbar color="secondary">
    <ion-title>
      Ionic App
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true" class="ion-padding">

  <ion-button (click)="openModal()">Open Modal</ion-button>

  <p *ngIf="dataReturned">{{dataReturned}}</p>


</ion-content>

Here we are also displaying data returned from Modal in the dataReturned variable.

 

#6 Import Modal Module in Home

To use a Modal component, we usually import its component in the EntryCompoents property of Module in whose component we are going to call it.

But in our case, the MyModal Page is having its own module in the my-modal.module.ts file. So we need to imports its module in the home.module.ts file to use it in the Home component.

// home.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { HomePage } from './home.page';

import { HomePageRoutingModule } from './home-routing.module';
import { MyModalPageModule } from '../modals/my-modal/my-modal.module';


@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    IonicModule,
    HomePageRoutingModule,
    MyModalPageModule
  ],
  declarations: [HomePage]
})
export class HomePageModule { }

 

#7 Run Application

That's it now you can run your application in the browser itself to see it working. Run following command in the terminal:

Find source code in GitHub repository here

$ ionic serve --open

 

Conclusion: We have successfully created the Ionic application with a working Modal component. Also discussed how to pass data from parent component(HomePage) to Modal component(MyModalPage) .Then calling the dismiss() method to pass data back to HomePage.

Subscribe
Notify of
14 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

OH MY GOD. Thank you a million times! #6 saved my multi-hour struggle. I could not get the ngIf directive to work on my modal no matter what I tried. I had the CommonModule import on the modal module and the parent module. There were no problems on any other components. I tried everything and was thinking of giving up.

Your tip of importing the module of the modal itself into the calling module was pure genius. I am no Angular expert but this…this got me out of a rut. You’ve got yourself a follower.

Thanks!

como se puede pasar datos de tipo array o vectores a la pagina modal que se crea?

[How can array type data or vectors be passed to the modal page that is created?
]

please give demo with the examples

Its possible pass an html or an content to modal?

Matthew Harris

BUG REPORT:
You have got these two lines switched around, they are trying to assign to each others params (id to title, title to id):

ngOnInit() {
console.table(this.navParams);
this.modelId = this.navParams.data.paramTitle;
this.modalTitle = this.navParams.data.paramID;
}

Matthew Harris

Theory question: I’m still learning but I thought async await was the better replacement for method.then() style coding.

In the home.page.ts update you have an async method but then drop back to using modal.onDidDismiss().then() style for the onDidDismiss event handler.

Is there a technical reason for this? Or was this perhaps just copied in from some docs somewhere or something like that?

why it’s not working for my app. I did same you.
Error: StaticInjectorError(AppModule)[ModalScanPage -> NavParams]:
StaticInjectorError(Platform: core)[ModalScanPage -> NavParams]:
NullInjectorError: No provider for NavParams!