Adding modals to an Ionic app
permalinkModals are a big thing in apps. You see them almost everywhere for small detail transactions.
In this article, I'll show you how to add your own modal to an Ionic app.
The result will look like this.
This tutorial will pick up from our starting Ionic app, which you can download from GitHub.
Modals in an Ionic app permalink
We will be adding a modal to our first tab page. Open up the tab1.page.ts
file.
Start by creating a function which we can call through the HTML in a second. This function will be an async
function and call the modalController to create a certain modal.
async presentModal() {
const modal = await this.modalController.create({
component: DetailPage
});
return await modal.present();
}
We do have to register the modalController
in our constructor.
constructor(public modalController: ModalController) {}
And you might have spotted we use a component called DetailPage
so let's go ahead and create that one.
ng g page Detail
This will generate the DetailPage for us. (Make sure you import the detail page in the tab1.page.ts)
Calling the modal permalink
We can call the presentModal
function from our tab1.page.html
file to prompt the modal.
<ion-button (click)="presentModal()" expand="block">Show Modal</ion-button>
This will create a button, which on click, will open the detail modal.
However, when this happens, you might have spotted there is no way to close the modal now.
Luckily we can leverage a global modalController
by injecting it in the detail.page.ts
file.
constructor(public modalController: ModalController) {}
Then we can create a dismiss function, which will handle the dismissal of the modal.
dismiss() {
this.modalController.dismiss();
}
It's quite common to have a back button on the detail page that will dismiss the modal so let's add one of those in detail.page.html
.
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-button color="white" (click)="dismiss()">
<ion-icon name="arrow-back"></ion-icon>
</ion-button>
</ion-buttons>
<ion-title>Detail</ion-title>
</ion-toolbar>
</ion-header>
We can even add a button on the page that will also dismiss the modal.
<ion-content fullscreen class="ion-padding">
<ion-button (click)="dismiss()" expand="block">Dismiss Modal</ion-button>
</ion-content>
This button will do the same, dismiss our modal.
And there you go, modals in Ionic are super easy and useful. They can even pass and return data, which we'll discuss in another topic.
You can find today's code on GitHub.
Thank you for reading, and let's connect! permalink
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter