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. This is an updated version of the latest Ionic 6 Angular project.
Furthermore, there are three goals behind in this Ionic latest 6 tutorial
- First, we will see how to implement the Ionic modal.
- Secondly, how we can pass data to and from the Ionic modal?
- Lastly, how do we customize ionic Modal design styles?
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
Set up and configure the Ionic modal example project
With the release of ionic version 4, the Ionic framework is 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.
How to use an Ionic modal Popovers controller?
We’ll demonstrate an example of how to use modal in an Ionic project. Here is what we are planning, let’s 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 add 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 a string variable that gets data from modal to page when we close are modal. Here on the home page, we show data only when we have data for dataFromModal using the 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 an Ionic modal controller and the website is an object variable that contains data that we want to send to our Ionic modal setting.
How to open the Ionic modal controller?
We first need to import and inject a modal controller on our consumer page. Once we have a modal object we can call create a method to create and configure settings for our modal page. Next to present method allows 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 to the page where we are using it, in our case we are using modal on the home page. As the modal can’t access through the router and we are not using the modal tag on our consumer page, we need to add our modal component in the declaration entry of the consumer page module.
We have to add the 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 the Ionic Modal popup 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 an object to configure the 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 the page to the 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 the @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 closed 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 display 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 the Ionic modal to the 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 confirmed.
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 the Ionic modal?
The ionic modal controller has a 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 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 the ionic modal size or 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 the 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’s add our custom modal style global.scss to change the Ionic modal size or width size.
ion-modal.setting-modal {
--ion-background-color:#f12000;
--border-radius: 10px;
--max-height: 55%;
--max-width: 80%;
--width: 80%;
--height: 50%;
--border-style: dotted;
--border-color: #428cff;
--border-width: 5px;
}
Where .setting -modal is the name of the CSS class which we have specified during modal creation in a page.
How to change the Ionic modal background to transparent?
By default Ionic modal background is grey in 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 provides uses custom CSS properties to customize the modal style and we have used these customized properties above example. Here is a list of custom CSS properties for the modal.
Name | Description |
–backdrop-opacity | The 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 | The border width of the modal content |
–height | Height of the modal |
–max-height | Maximum height of the modal |
How to use the Ionic modal using promise?
We can also use promise instead of async to create a 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');
}
On the modal consumer page, we can access roles and use promises to create a 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.
Properties | Description |
---|---|
component | Name of a component to display inside of the modal. |
componentProps | What data to pass to the modal component. |
cssClass | Name of custom CSS class name where we apply style for the modal. We can have multiple classes provided they should be separated by spaces. |
mode | The mode determines which platform styles to use. |
swipeToClose | If true, the modal can be swiped to dismiss. Only applies in iOS mode. |
enterAnimation | Animation to use when the modal is presented. |
leaveAnimation | Animation to use when the modal is dismissed. |
showBackdrop | If true, a backdrop will be displayed behind the modal. |
presentingElement | The 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. |
keyboardClose | If true, the keyboard will be automatically dismissed when the overlay is presented. |
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
- How to implement an ionic slider
- Complete guide on an ionic grid with an example
- How to implement an ionic alert controller.
- How to implement an ionic table with pagination.
- How to use ionic skeleton component.
- How to create a different ionic list.
Hi is this still valid for ionic 5? the CSS customization?
I don’t think there will be issues, as modals are outside of the component and I updated to the latest Ionic 6.