Closing Modal in Ionic/Stencil PWA Toolkit


#1

How do I programmatically close a modal from itself in a PWA Toolkit app? I understand the toolkit is beta, but I was wondering if there is a way to do this in the current PWA toolkit version. I understand that there is a way to do this with a close/back button in Angular/Cardova based apps (Angular ViewController), but how do we do this for plain vanilla/ionic PWAs? Thanks …


#2

Late to the party but I found the solution on the slack channel provided by @corymc. So if that could helps someone in the future too, here his solution:

@Element() el: HTMLElement;

async closeModal() {
        await (this.el.closest('ion-modal') as HTMLIonModalElement).dismiss();
    }

#3

This does work, and you shouldn’t need the as HTMLIonModalElement now.

However, the approach I like to use is this thanks to @simonhaenisch

Pass the modalCtrl from within the parent component:

@Prop({ connect: 'ion-modal-controller' })
 modalCtrl: HTMLIonModalControllerElement;

...

async openModal() {
    const modalCtrl = await this.modalCtrl.componentOnReady();
    const modalOptions: ModalOptions = {
      component: 'modal-component',
      componentProps: {
          modalCtrl
      }
    };
    const modal = await this.modalCtrl.create(modalOptions);
    modal.present();
  }

Then within the modal-component you can simply:

@Prop()
  modalCtrl: HTMLIonModalControllerElement;
...

close() {
  this.modalCtrl.dismiss();
}