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…

By.

•

min read

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</pre>
The current version of <code>@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
</pre>
move to the application folder
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ cd ionic-modal-demo</pre>
then open application folder in Visual Studio Code in installed by running
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">$ code .</pre>
 
<h3>#3 Create Modal Page</h3>
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 <code>generate command to create a new page with MyModalPage component in modals page.
$ ionic generate page modals/my-modal</pre>
Above command will create a new page in modals folder as shown below:

<img class="alignnone wp-image-3970 size-full" src="https://www.freakyjolly.com/wp-content/uploads/2019/02/Pasted-into-Ionic-45-How-to-Use-Ionic-Modal-Popovers-and-Pass-Data-and-Receive-Response.png" />

 
<h3>#4 Update Modal Page</h3>
After creating the MyModal page, let's update its template and component class files.

Update the <strong>my-modal.page.html</strong> file with following HTML template
<pre><code class="language-markup"><!-- 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></pre>
Here we are just displaying the value passed from Home page in the <code>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();
  }</pre>
Finally, the <strong>home.page.ts</strong> file will look like this:
<pre class="wp-block-prismatic-blocks"><code class="language-javascript">// 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();
  }

}
</pre>
Here we are passing data to the Modal using <code>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></pre>
Here we are also displaying data returned from Modal in the <code>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</pre>
<a href="https://www.freakyjolly.com/wp-content/uploads/2019/02/ionic-modal-demo.gif"><img class="aligncenter size-full wp-image-3971" src="https://www.freakyjolly.com/wp-content/uploads/2019/02/ionic-modal-demo.gif" alt="" width="266" height="235" /></a>

 

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

18 responses to “Ionic 5|4 How to Use Ionic Modal Popovers and Pass Data and Receive Response”

  1. ricardo Avatar
    ricardo

    •

    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?
    ]

    1. anRoswell Harris Maiden Avatar
      anRoswell Harris Maiden

      •

      You can pass an array object

  2. shubham Avatar
    shubham

    •

    please give demo with the examples

  3. Firmo Avatar
    Firmo

    •

    Its possible pass an html or an content to modal?

  4. Matthew Harris Avatar
    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;
    }

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hey, Matthew thanks for pointing out 🙂

  5. Matthew Harris Avatar
    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?

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Matthew, async await is a traditional way to work with promises but we need a const here. In post, I have used both methods to showcase its usage. It’s up to the developer which styles is preferred 🙂

      1. Matthew Harris Avatar
        Matthew Harris

        •

        Thanks! I wonder if it was just a style thing or if there was something I didn’t yet know about TS/JS

  6. HaPham Avatar
    HaPham

    •

    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!

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Make sure you have updated Ionic CLI to the latest version as there was the same issue with the beta version

  7. teest Avatar
    teest

    •

    ionic v4 doesn’t have navParams, so this tutorial will NOT work.

    1. Jolly.exe Avatar
      Jolly.exe

      •

      Hi Teest, just give it a try, will work fine as NavParams is available under ‘@ionic/angular’ package

      1. princepatel Avatar
        princepatel

        •

        model.onDidDismiss().then((res) => {
        console.log(res)
        })

Leave a Reply

Your email address will not be published. Required fields are marked *