How to declare and use modals in Ionic v4

Creating a modal

import {Component} from '@angular/core';@Component({
templateUrl: 'date-picker.html',
styleUrls: ['./date-picker.scss'],
selector: 'app-date-picker'
})
export class DatePickerModal {
}

Declaring the modal’s module

import {NgModule} from '@angular/core';
import {IonicModule} from '@ionic/angular';
import {CommonModule} from '@angular/common';
// The modal's component of the previous chapter
import {DatePickerModal} from './date-picker';
@NgModule({
declarations: [
DatePickerModal
],
imports: [
IonicModule,
CommonModule
],
entryComponents: [
DatePickerModal
]
})
export class DatePickerModalModule {}

Lazy loading

Using the modal

import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {IonicModule} from '@ionic/angular';
// The modal's module of the previous chapter
import {DatePickerModalModule} from '../../../../modals/core/date-picker/date-picker.module';
@NgModule({
declarations: [
NewAdStepAvailabilityComponent
],
imports: [
IonicModule,
CommonModule,
DatePickerModalModule
],
exports: [
NewAdStepAvailabilityComponent
]
})
export class NewAdStepAvailabilityModule {}

Calling the modal and passing parameters

async openModal() {
const modal: HTMLIonModalElement =
await this.modalController.create({
component: DatePickerModal,
componentProps: {
aParameter: true,
otherParameter: new Date()
}
});

modal.onDidDismiss().then((detail: OverlayEventDetail) => {
if (detail !== null) {
console.log('The result:', detail.data);
}
});

await modal.present();
}

Getting the parameters in the modal and closing the modal with a result

import {Component} from '@angular/core';
import {ModalController, NavParams} from '@ionic/angular';
@Component({
templateUrl: 'date-picker.html',
styleUrls: ['./date-picker.scss'],
selector: 'app-date-picker'
})
export class DatePickerModal {

myParameter: boolean;
myOtherParameter: Date;
constructor(private modalController: ModalController,
private navParams: NavParams) {
}
ionViewWillEnter() {
this.myParameter = this.navParams.get('aParameter');
this.myOtherParameter = this.navParams.get('otherParameter');
}
async myDismiss() {
const result: Date = new Date();

await this.modalController.dismiss(result);
}
}

Cherry on the cake 🍒🎂

Freelancer by day | Creator of DeckDeckGo by night | Organizer of the Ionic and IndieHackers Zürich Meetup

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store