How to implement an ionic modal controller in details

Ionic modal is a form of temporary UI that slides into the screen, over the page content, and is often used for login/registration forms, composing messages, or presenting app configuration options for example. Like a modal controller, Ionic has lots of pre-built components, which we can ready to use like action-sheet, loading, toast controller, and more.

Furthermore, there are three goals behind this chapter. First, we will see how to implement the Ionic modal. Secondly, how we can pass data to and from ionic modal, and lastly how we customize ionic Modal design. Let’s get started.

Prerequisites:
To create and run an Ionic project, We need nodejs and Ionic CLI already install in our system, if not then check how to install nodejs and Ionic in Ubuntu. Ionic CLI allows us to create an Ionic project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install the Ionic CLI, open a terminal, and run the following command:

npm install -g @ionic/cli

Setting up and configure Ionic modal popup project

With the release of ionic version 4, the Ionic framework no longer limited to angular, we can create the ionic projects in different front-end frameworks like Angular, Vue, and React. Let first create a blank Ionic Angular project. We need a component that will act as a modal component and let’s create a modal component called settings.

ionic start modalApp --type=angular
ionic generate component settings

Here’s a quick screenshot of what we’ll be building.

Ionic modal example
Ionic modal controller

How to use Ionic modal controller ?

We’ll demonstrate an example of how to use modal in an Ionic project. Here is what we are planning, let create a home page, we have a button with a setting icon at the top right corner of the home page template. The ionic modal popup setting component is loaded by clicking on the setting icon button in the home template. The Ionic modal controller can be created and dismissed from the modal controller. Edit the home.page.html template adds the following code.

<ion-header>
  <ion-toolbar color="primary">
    <ion-buttons slot="end">
      <ion-button (click)="settings()">
        <ion-icon name="settings"></ion-icon>
      </ion-button>
    </ion-buttons>
    <ion-title>
      Ionic Modal Controller
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    <ol>
      <li>Passing data from page to Modal</li>
      <li>Receving data from Modal</li>
    </ol>
    <h5 *ngIf="dataFromModal">Data from Modal : {{ dataFromModal }}</h5>
  </div>
</ion-content>

The dataFromModal is string variable which get data from modal to page when we close are modal. Here in home page, we show data only when we have data for dataFromModal using ngIf directive. Edit our Ionic popup consumer page in our case home.page.ts file.

import { Component } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { SettingsComponent } from '../settings/settings.component';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  dataFromModal: string;
  website = { name: 'Edupala.com', created: '12-July-2016', topic: 'Tutorial on Ionic' };

  constructor(private modalController: ModalController) {}

  async settings() {
    const modal = await this.modalController.create({
      component: SettingsComponent,
      componentProps: { website: this.website },
      cssClass: 'setting-modal',
      backdropDismiss: false,
    });

    modal.present();

    const modalData = await modal.onWillDismiss();
    this.dataFromModal = modalData.data.name ? modalData.data.name : modalData.data.ionic;
  }
}

In our constructor we need to inject Ionic modal controller and website is object varaible which contain data which we want to sent to our Ionic modal setting.

How to open Ionic modal controller ?

We first need to import and inject a modal controller on our consumer page. Once we have modal object we can call create method to create and configure setting for our modal page. Next present method allow us to open modal on our page.

Import Ionic modal component inside our consumer component module

Once we create our modal component we have to import it on our page where we are using it, in our case we are using modal on the home page. As modal can’t access through the router and we are not using the modal tag in our consumer page, we need to add our modal component in the declaration entry of the consumer page module. We have to add SettingComponent modal in our home.module.ts file in declarations. The ionic modal will not be loaded when it is opened, but rather when the module that imports the modal’s module is loaded.

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 { SettingsComponent } from '../settings/settings.component';

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

How to pass data to Ionic Modal page ?

Ionic modal can be created using a modal Controller and we can customize modal options in the modal controller’s create() method. In the create method we have object to configure modal setting and we can use componentProps property of the modal options to pass data of any type like string or object to the modal page. In our case, we are sending an object called a website from page to modal component. Ionic Modal controllers programmatically control the modal component. Inside the Ionic home typescript, we are passing data to modal, here we are using the variable website. Ionic modal can be dismissed after creation by calling the dismiss() method on the modal controller.

 website = { name: 'Edupala.com', created: '12-July-2016', topic: 'Tutorial on Ionic' };

const modal = await this.modalController.create({
      component: SettingsComponent,
      componentProps: { website: this.website }
});

How to Retrieve data from page to Ionic Modal component

During the creation of a modal, data can be passed in through the componentProps. To retrieve passed data into the Ionic modal controller, we can either set it as an @Input or access it via NavParams on the ModalPage. To get data from page to modal, we are using @Input decorator method and we need to define website variables in the modal component, it should have the same name as a variable which we pass value from our page, where we are passing data from page to modal.

import { Component, Input } from '@angular/core';
import { NavParams, ModalController } from '@ionic/angular';

@Component({
  selector: 'app-settings',
  templateUrl: './settings.component.html',
  styleUrls: ['./settings.component.scss'],
})
export class SettingsComponent {
  @Input() website: object;

  constructor(private navParams: NavParams, private modalController: ModalController) {
    // componentProps can also be accessed at construction time using NavParams
    console.log(this.navParams.get('website'));
  }

  // Sending data from Ionic modal to page
  settingIonic(version: string) {
    this.modalController.dismiss(
      { ionic: version },
      'confirm'
    );
  }

  closeModal() { this.modalController.dismiss(); }

  settingJavascript() { }

  settingCommon(name: string) {
    this.modalController.dismiss(
      { name },
      'confirm'
    );
   }
}

We can see that the modal can be close using dismiss method of the modal controller. The dismiss method can be return void or data. Edit the following code for our Ionic modal settings template, here we displaying data that we got from the page and we have a list of an item containing three methods. We have a button with a close icon and clicking on it will dismiss the modal without any return data.

    <ion-content>
  <ion-toolbar color="tertiary">
    <ion-buttons slot="end">
      <button ion-button icon-only color='black' (click)="closeModal()">
        <ion-icon name="close"></ion-icon>
      </button>
    </ion-buttons>
    <ion-title>Ionic Modal Title</ion-title>
  </ion-toolbar>
  <ion-list>
    <ion-list-header>
      <ion-label>Data From Page : {{ website | json }}</ion-label>
    </ion-list-header>
    <ion-item (click)="settingIonic('Ionic 6')">Ionic</ion-item>
    <ion-item (click)="settingCommon('Angular 11')">Angular</ion-item>
    <ion-item (click)="settingCommon('Javascript')">Javascript</ion-item>
  </ion-list>
</ion-content>

How to pass data from Ionic modal to page ?

In the modal component template, we have three options list, and clicking on each item will call dismiss method of the modal and pass data from modal to page. On clicking on the Ionic option from the Ionic list, we are passing ionic data with the value of version 6 and role as confirm.

    this.modalController.dismiss(
      { ionic: version },
      'confirm'
    );

On the parent page, we can receive data from the modal using the onWillDismiss method which returns data from the modal dismiss method. On the parent page of the modal component, we can get data as.

// modal create code 
.....
modal.present();

modal.onDidDismiss().then((modelData) => {
      if (modelData !== null) {
        this.modelData = modelData.data;
        console.log('Modal Data : ' + modelData.data);
      }
}

How to close Ionic modal ?

The ionic modal controller has few methods like create and it also has dismiss() method. We can use dismiss method to close our modal. The dismiss method can be a close and return role, with and without data and we have discussed above of getting data and role from modal to page.

this.modalController.dismiss(); // without data and role

this.modalController.dismiss({name: 'edupala'}, 'confirm'); // with data and role

How to Customize ionic modal style ?

In our home.page.ts file, we have set modal options, it has a property called cssClass where we added our custom class name called setting-modal. With this custom CSS class, we can control the Ionic modal style like ionic modal size, ionic background color, and position, we need to add our modal style inside global.scss and this is because the modal controller works at the root level.

In Angular, the CSS style of the component is scoped only to the element of the component. Even though the Ionic modal element is presented within a component or a page but ion-modal element is appended outside of the current component or page. So we have to add ion-modal element style only in src/global.scss. and let add our custom modal style in global.scss

.setting-modal .modal-wrapper {
    --ion-background-color:#f12000;
    --border-radius: 20px;
    --max-height: 55%;
    --max-width: 80%;
    --width: 80%;
    --height: 50%;
    --border-style: dotted;
    --border-color: #428cff;
    border-width: 5px;
    top: 20%;
}

Where .setting -modal is name of CSS class which we have specified during modal creation in a page.

Ionic modal style
Ionic modal style

How to change the Ionic modal background to transparent ?

By default Ionic modal background is grey color, to make our ionic modal background transparent we need to add the following code to global.scss file. We need to set our modal –backdrop-opacity of CSS custom properties to zero.

//Modal background transparent
.setting-modal {  // Modal cssClass class name
    ion-backdrop {
      --backdrop-opacity: 0;
    }
}

Ionic modal provide use custom CSS properties to customize the modal style and we have used these customize properties above example. Here is a list of custom CSS properties for the modal.

Name Description
--backdrop-opacity Opacity of the backdrop
--background Background of the modal content
--max-width Maximum width of the modal
--min-height Minimum height of the modal
--min-width Minimum width of the modal
--width Width of the modal
--border-color Border color of the modal content
--border-radius Border radius of the modal content
--border-style Border style of the modal content
--border-width Border width of the modal content
--height Height of the modal
--max-height Maximum height of the modal

How to use Ionic modal using promise ?

We can also use promise instead of async to create modal. And in the modal controller, we can send back not only the data but also the roles as, In our setting modal, syntax this.modalController.dismiss( data, role) and on the modal consumer may be based on the role we have different activity.

In the ionic modal component settings, we can have

// Sending data from modal to page, have data and role confirm
 settingIonic(version: string) {
   this.modalController.dismiss(
     { message: 'Ionic version 5.'}, 
     'confirm'     //Role name
   );
 }

 closeModal() { 
  // data null and role cancel
   this.modalController.dismiss(null, 'cancel'); 
 }

In the modal consumer page, we can access role and used promise to create modal.

settings() {
    this.modalController.create({
      component: SettingComponent,
      componentProps: { website: 'edupala.com' },
      cssClass: 'setting-modal',
      backdropDismiss: false,
    }).then((modalEl) => {
	modalEl.present();
	return modal.onDidDismiss();
    }).then((result) = > {
	if (result.role === 'confirm') {
	     console.log(result.data)
         }
     });
}

Ionic modal properties

When creating a new ionic popup modal using the method create(), we can pass an object to configure the Ionic modal. The following configuration properties are supported by Ionic modal options.

PropertiesDescription
componentName of component to display inside of the modal.
componentPropsWhat data to pass to the modal component.
cssClassName of custom CSS class name where we apply style for modal. We can have multiple classes are provided they should be separated by spaces.
modeThe mode determines which platform styles to use.
swipeToCloseIf true, the modal can be swiped to dismiss. Only applies in iOS mode.
enterAnimationAnimation to use when the modal is presented.
leaveAnimationAnimation to use when the modal is dismissed.
showBackdropIf true, a backdrop will be displayed behind the modal.
presentingElementThe element that presented the modal. This is used for card presentation effects and for stacking multiple modals on top of each other. Only applies in iOS mode.
keyboardCloseIf true, the keyboard will be automatically dismissed when the overlay is presented.
Ionic popup configuration properties

Conclusion
We have explored how to use Modal in the Ionic project and we have demonstrated how to customize our modal style using cssClass property of modal options. Passing data to modal and from modal is easy.

Related posts

Leave a Comment

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

Scroll to Top