Sampath
Sampath

Reputation: 65870

Open a 2nd Modal and then close the 1st modal

I have two Modals and the problem I'm having is with closing the 1st modal after 2nd modal has been opened.

I have tried this. But then it never opens the 2nd Modal.

This is within the 1st Modal

async next(): Promise<void> { // try to open 2nd Modal and after that close the 1st Modal
  await this.showSeeAgainModal();
  this.cancel();
}

cancel(): void {
  this.modalController.dismiss();
}

async showSeeAgainModal(): Promise<void> { // This is the 2nd Modal
  const modal: HTMLIonModalElement = await this.modalController.create({
    component: SeeAgainPage,
  });

  modal.onDidDismiss().then(async (res) => {
  });

  return await modal.present();
}

Update: I have tried with 2 ModalControllers. i.e. one for the parent and other for a child. But that too didn't work.

Upvotes: 3

Views: 2346

Answers (2)

htmn
htmn

Reputation: 1675

The problem is that you are calling this.modalController.dismiss(), which closes the active second modal. You need to have a reference to your first modal if you want to dismiss it from the second one. Pass a dismissFirstModal function as a componentProp to the second modal and take advantage of the ionModalDidPresent event, which is emitted after the modal has presented. Here is a working example

first.component.ts

constructor(public modalController: ModalController){}

async presentFirstModal() {
  const dismissFirstModal = () => {
    modal.dismiss();
  };
  const modal = await this.modalController.create({
    component: SecondComponent,
    componentProps: {dismissFirstModal: dismissFirstModal}
  });
  return await modal.present();
}

second.component.ts

@Input() dismissFirstModal;

constructor(public modalController: ModalController){}
ngOnInit() {}

async showSeeAgainModal(): Promise<void> {
  const modal = await this.modalController.create({
    component: SeeAgainPage,
  });

  modal.addEventListener('ionModalDidPresent', () => {
    this.dismissFirstModal()
  })

  return modal.present();
}

Upvotes: 2

alexander.sivak
alexander.sivak

Reputation: 4710

Try to use id when creating a new modal element. For example

showSeeAgain(id: string) {
  this.modalCtrl.create(
  {
    component: CreateBookingComponent,
    id: id // here is the id of a new modal
  }).then(
   modalElement => {
      modalElement.present();
      return modalElement.onDidDismiss();
    }).then(data => console.log(data));          
}

cancel(id: string) {
  this.modalCtrl.dismiss({message: 'I am closing a modal'}, 'confirm', id);
}

and then you can close a modal when dismissing by using id.

Upvotes: 0

Related Questions