To begin, you should develop a generic service that wraps the modal functionality and also maintains the state of which modal is returning what data (especially if multiple modals are opened simultaneously).
async showModal(modalPage, fullscreen: boolean, componentProps?) {
let resolveFunction: (res: any) => void;
const promise = new Promise<any>(resolve => {
resolveFunction = resolve;
});
const modal = await this.modalCtrl.create({
component: modalPage,
cssClass: fullscreen ? 'full-screen-modal' : 'half-screen-modal',
componentProps
});
modal.onDidDismiss().then(res => {
resolveFunction(res);
});
await modal.present();
return promise;
}
Next, structure your modal page like so:
import { Component, OnInit } from '@angular/core';
import { DisplayService } from 'src/app/services/display/display.service';
@Component({
selector: 'app-rating',
templateUrl: './my-modal.page.html',
styleUrls: ['./my-modal.page.scss'],
})
export class MyModal implements OnInit {
constructor(private displayService: DisplayService) {}
ngOnInit() {
}
sendValue() {
// Perform any necessary async tasks here before closing the modal
this.displayService.closeModal({...returnData}); // Optionally pass return Data here if needed in calling page
}
}
Finally, your parent page will need to be configured as shown below to display the modals and handle the returned data:
async openModal(){
await this.displayService.showModal(MyModal, false, null).then( res => {
// Wait for modal to return data upon closing
if (res.data.value1){
const payload = {rating: res.data.value1, remarks: res.data.value2};
// Make API call
this.displayService.showToast(`Thank you`, 'success');
} else {
this.router.navigate([`failed-route-view/`]);
}
});
}