How to dismiss multiple modals in ionic v4? solution is here!

Using Ionic v4 Create Multiple modals . we can hide modal by using dismiss() . but it hide only top overlay modal. need to hide appropriate modal. here is a solution

first you need to create ionic modal using by Modal Options
after mention component in modal options, beneath that need to mention modal id

 async ShowEmployeelistModel(){
    const modal = await this.modalCtrl.create({
      component: EmployeeListComponent,
      id:"FlowEmployee" 
    });
    return await modal.present();
  }

above code show you how to create modal with id

now if you want to hide that modal

in dismiss method need to pass id as parameter

 this.modalCtrl.dismiss(null, null, "FlowEmployee");

above code mention that passing parameter .
first one parameter is data optional
second one role optional
third one id optional

 this.modalCtrl.dismiss();

in the above code . i did not mention id . so it will dismiss top overlay modal

8 Likes

Ok so I had the same issue and I solved it this way. The solution is to store all the modal instances using a service in an array. Then use a loop and dismiss all the modals refering them from that array.

modal.html

    <ion-button (click)="openModal()"> Open Modal <ion-button>
    <ion-button (click)="close()"> Close Modals <ion-button>

modal.service.ts

modalInst=[];
i=0;

storeModal(x)
{
       this.modalInst[this.i]=x;
       this.i++;
}

modal.ts

openModal()
{
    var modal = await this.viewCtrl.create({
    component: ModalPage
   });

 this.service.storeModal(modal);// storing modal instances in an array
   return await modal.present();
}

close()
    {
        for(var i=0; i< this.service.modalInst.length; i++)
         {
            this.service.modalInst[i].dismiss();
         }
    }
3 Likes

Brother… you just save my life… Thanks… it worked as a charm… i needed to close 3 modals…