Launch another modal and then deactivate the initial modal

Having two Modals has presented a challenge for me when it comes to closing the first modal after the second one is opened.

I attempted a solution, but it prevented the second Modal from opening altogether.

This code snippet below belongs to the first 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 experimented with using 2 ModalControllers - one for the parent and one for the child. Unfortunately, this approach did not resolve the issue either.

Answer №1

One issue arises when the this.modalController.dismiss() method is called as it closes the currently active second modal. To address this, it is crucial to have a reference to the first modal in order to dismiss it from the second one. By passing a function named dismissFirstModal as a componentProp to the second modal and utilizing the ionModalDidPresent event emitted post-modal presentation, this challenge can be resolved. For a practical demonstration, refer to this 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();
}

Answer №2

Make sure to utilize the id attribute when generating a fresh modal element. Here is an example:

showSeeAgain(id: string) {
  this.modalCtrl.create(
  {
    component: CreateBookingComponent,
    id: id // This is the assigned id for the 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);
}

You can then close a modal using its id upon dismissal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger Angular Animation when there is a modification in the DOM element's appearance or styling

I've been working on implementing a fade-in animation in my Angular App that triggers every time the background changes, but I'm facing some challenges with it. Here's the relevant code snippet: HTML: <div @fadeIn [style.backgroundImag ...

Converting a string array to an object leads to an issue where the element implicitly has an 'any' type, as the expression of type 'string' cannot be used to index the type '{}'

Hey there, I have some code that looks like this: export type Options = Record<string, string> export type CheckboxValue<T extends Options> = Partial< Record<keyof T, boolean> > export type Checkbox<T extends Options> = ...

Methods for invoking a JavaScript function from TypeScript within an Angular2 application

Hey there! I'm looking to execute a regular JavaScript function from a TypeScript file. Let's say I have a JavaScript file called test.js and it's been imported into the index.html of my application. Now, I want to invoke the test() functi ...

Transferring information from childA component through its parent component and into childB component

In my project, there is a main parent component with two child components: 1. app-search-list and 2. app-vertical-menu The data is passed from the app-search-list (childA) component to its parent component, and then from the parent to the app-vertical-men ...

Reducing SCSS import path in Angular 7

Creating a component that is deeply nested raises the issue of importing shared .scss files with long paths: @import '../../../app.shared.scss'; This hassle doesn't exist when it comes to .ts files, thanks to the configuration in tsconfig. ...

Discovering an entry that lacks a specific value within an array in the records

Currently, I am utilizing sequelize along with typescript in a node environment (with a postgresql database). Here is the model that I have defined: id: number, someField: string, arr1: number[], arr2: number[] My objective is to retrieve all records wher ...

Is it possible to multitask within a structural directive by performing two actions simultaneously?

I want to develop a custom structural directive with the following behavior: <p *myDirective="condition">This is some text</p> If condition is false, the <p> tag will not be displayed at all. If condition is true, the <p> tag wi ...

Angular 2: Embracing the Power of Hierarchical Selection

My goal is to create cascading selects where each option in a dropdown menu can lead to its own set of unique child options. This will result in a hierarchical structure of selectable items. To accomplish this, I have defined a class named fieldSelect tha ...

Issue with Highcharts: Y-axis values are not being bound correctly

Having trouble binding certain values to the Y axis of a highchart. The first value from the array displays correctly, but the rest are showing up incorrectly. https://i.sstatic.net/qmUXT.png chartOptionsLine: any = { yAxis: { categories: [&apo ...

What is the process for transforming a string literal type into the keys of a different type?

Imagine having a string literal type like this: type Letters = "a" | "b" | "c" | "d" | "e"; Is there a way to create the following type based on Letters? type LetterFlags = {a: boolean, b: boolean, c: bool ...

Error with application tab directive based on user roles

My custom directive, the `has-role.directive.ts`, is responsible for displaying or hiding tabs in my application based on the user's role. However, I encountered an issue where after logging out, the directive fails to update the view and the tab rema ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Can data be filtered based on type definitions using Runtime APIs and TypeDefs?

My theory: Is it feasible to generate a guard from TypeDefs that will be present at runtime? I recall hearing that this is achievable with TS4+. Essentially, two issues; one potentially resolvable: If your API (which you can't control) provides no ...

Struggling to map a JSON file in a NextJS project using Typescript

I'm a beginner in JS and I'm currently struggling to figure out how to display the data from a json file as HTML elements. Whenever I run my code on the development server, I encounter the error message: "props.books.map is not a function&q ...

Tips for managing multiple projects in Angular 7 simultaneously

Our team is currently working on an application with two separate workspaces. One workspace serves as the main project while the other is exported as a module to our private npm repository. To access this module, we retrieve it through our package.json f ...

Managing two subscriptions based on conditions in Angular

I'm currently working on a component that includes the following code snippet: this.service().subscribe((result) => { this.service2(result).subscribe((result2) => //other code }} As I strive to follow best practices in Angular development, I&ap ...

Issue with Build System CTA's/Callback function functionality not operational

I have encountered an issue with my build/design system. Although everything works fine during development, when I publish my package and try to use the callback function, it does not return the necessary data for me to proceed to the next screen. I tried ...

How can I retrieve query parameters passed from an Angular application in PHP?

I'm trying to figure out how to retrieve data from query parameters sent by an Angular application in PHP. Unfortunately, I don't have much experience with PHP. Is there anyone willing to lend a hand? ...

Enhancing many-to-many relationships with additional fields in Objection.js

I have a question that I haven't been able to find a clear answer to in the objection.js documentation. In my scenario, I have two Models: export class Language extends BaseId { name: string; static tableName = 'Languages'; st ...

Securing Your Subscription Key in Azure API Management

Technology mix The API is deployed within a WebApp environment. API Management is set up and the WebApp is configured as a Web service URL. The user interface is developed using Angular application, which accesses API Management endpoints to exhibit data ...