Home > front end >  How self dismiss a modal in Ionic 5
How self dismiss a modal in Ionic 5

Time:04-13

I have a component that opens a modal executes some asynchronous action, and I would like to self dismiss the modal once the asynchronous function i.e fetchData resolves.

@Component({
})
export class MyComponent implements OnInit { 
  openModal() {
   const modal = await this.modalCtrl.create({
      component: MyModalComponent,
   });
   await modal.present();
  }
}

@Component({
})
export class MyModalComponent implements OnInit { 
  fetchData() {
    this.fetchData().subscribe((response) => {
       // do some stuff

       // Dismiss the modal here
    })
  }
}

CodePudding user response:

First, you have to create a generic service that wraps the modal fuctionality while also ensuring that you keep state of which modal is returning which data (in case you open multiple modals on top of one another).

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;

}

Then you make the modal page to be as follows:

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() {
    // do whatever async task you need to do here then close modal when finished
    this.displayService.closeModal({...returnData}); // Optionally pass return Data here if you need it in the calling page
  }

}

The finally your parent page should look like this to display your modals & act on the return data:

async openModal(){
    await this.displayService.showModal(MyModal, false, null).then( res => {
      // wait for the modal to return data when it exits
      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/`]);
      }
    });
  }

CodePudding user response:

A simpler way to do that is just to put in your function fetchdata() the Modal dismiss function. Follows an example:

  fetchData() {
    this.fetchData().subscribe((response) => {
       // do some stuff

       // Dismiss the modal here
       this.modalController.dismiss();            
  • Related