Guide to making a ng-bootstrap modal that retains a component's state

I am currently working on implementing a modal with Angular by following a tutorial on the ng-bootstrap website ( - in the "Components as content" section). However, I am facing a challenge where I want the component displayed in the modal to retain its state even after it is closed and reopened.

To illustrate this issue, I have created a simple example on Plunker: http://plnkr.co/edit/EJyZ6nF5WVAS9bvQycQe?p=preview

My goal is to have the text "Hello, A!" displayed when calling open() after calling openA(), but unfortunately, the state is not being preserved.

openA() {
  const modalRef = this.modalService.open(NgbdModalContent);
  modalRef.componentInstance.name = 'A';
}

openB() {
  const modalRef = this.modalService.open(NgbdModalContent);
  modalRef.componentInstance.name = 'B';
}

open() {
  const modalRef = this.modalService.open(NgbdModalContent);
}

How can I achieve this with the minimum setup? Are there any specific Angular documentation resources you recommend for better understanding of the situation?

Answer №1

Each time a new modal is launched with a component as its content, the component will be recreated (and destroyed when the modal is closed). Therefore, it is not possible to "persist" component instances.

Instead, it is recommended to maintain the model (data) that dictates the display and functionality of the component.

Answer №2

Implementing the windowClass option in the parent model

const parentModalRef = this.modalService.open(ParentModal, {
  centered: true,
  windowClass: 'refererToParent',
});

By using this, a class named "refererToParent" will be applied to the parent modal window. Make sure to remove the 'show' class from the parent modal window before opening the ChildModal. Then, open the ChildModal without a backdrop.

parent = document.getElementsByClassName('refererToParent').item(0)!;
parent.classList.remove('show')
const childModalRef = this.modalService.open(ChildModal, {
  backdrop: false
});

Add a listener to childModalRef to add the 'show' class back to the parent modal once the ChildModal is closed.

childModalRef.closed.subscribe(() => parent.classList.add('show'))

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

Triggering multiple subscription functions in Ionic 3 NGRX when a single state change occurs

I have developed an Ionic 3 application that utilizes NGRX for state management purposes. The app is designed to connect to a device via BLE technology. Within my connection page, where the BLE device is connected, I have implemented the following code: ...

Implement a universal Custom Validator to be applied to all FormControls across the entire application

We've encountered a scenario where a client proposed incorporating a custom validator to every field in their application, which comprises of over 1000 Angular formControls. I'm curious to know if there exists a method to universally alter the f ...

Ensuring Angular2 Javascript is validating only numerical input and not accepting characters

Access the full project here (excluding nodes_modules): Note: After running the project, all actions related to this issue can be found in the "Edit All" section of the website. Click on that to view the table. The main objective of this website section ...

Are the Angular tests passing even before the asynchronous call has finished?

When running the following Angular (4) test for a service, it appears to pass before the Observable returns and hits the expect statement. it('should enter the assertion', inject( [ MockBackend, CellService ], ( backend: MockB ...

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

Error in typescript: The property 'exact' is not found in the type 'IntrinsicAttributes & RouteProps'

While trying to set up private routing in Typescript, I encountered the following error. Can anyone provide assistance? Type '{ exact: true; render: (routerProps: RouterProps) => Element; }' is not compatible with type 'IntrinsicAttribu ...

An object may be null when its type is A or undefined, but we are certain it is not undefined

Since the release of version 4.8.4, the TypeScript compiler has been flagging an issue with the following code: type A = {v: number} function get_the_first<T>(xs: T[]): T | undefined { if (xs.length > 1) return xs[0]; else ...

Tips for altering the color of the MUI table sort label icon:

Does anyone know how to change the color of the table sort label icon from gray to red? I am having trouble figuring it out. Any recommendations or suggestions would be greatly appreciated. Here is the code I have been trying to work with: <TableSortL ...

Using NodeJS API gateway to transfer image files to S3 storage

I have been attempting to upload an image file to S3 through API Gateway. The process involves a POST method where the body accepts the image file using form-data. I crafted the lambda function in TypeScript utilizing the lambda-multipart-parser. While it ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

A collection of JSON data containing various diverse values

My classes are not specific and they look like this: type SyncReducerAction<TState> = (state: TState, ...args: any[]) => TState; type AsyncReducerAction<TState, TResult, TRest extends any[]> = { promise: (...args: TRest) => Promise< ...

How can I retrieve the `checked` state of an input in Vue 3 using Typescript?

In my current project, I am using the latest version of Vue (Vue 3) and TypeScript 4.4. I am facing an issue where I need to retrieve the value of a checkbox without resorting to (event.target as any).checked. Are there any alternative methods in Vue tha ...

Visual Studio Code is encountering issues when trying to start a Node application

I am in the process of setting up a workflow for an express app using TypeScript, Visual Studio Code, and gulp. Here is the structure of my project: src/ <-- source files Start.ts Server.ts models/ Contact.ts Organization.ts bin/ <- ...

Clicking on the image in Angular does not result in the comments being displayed as expected

I find it incredibly frustrating that the code snippet below is not working as intended. This particular piece of code was directly copied and pasted from an online Angular course I am currently taking. The objective of this code is to display a card view ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

Checking constructor arguments and code style issues

I need to ensure that the constructor parameter is validated correctly when an instance of a class is created. The parameter must be an object that contains exactly all the properties, with the appropriate types as specified in the class definition. If t ...

Select information from an array and store it within an object

I want to extract all objects from an array and combine them into a single object. Here is the current array data: userData = [ {"key":"firstName","checked":true}, {"key":"lastName","checked":true ...

Differences Between JavaScript and TypeScript Classes

I'm a novice when it comes to TypeScript and JavaScript classes! While learning TypeScript, I created a simple code snippet like this: class User { name: string; email: string; constructor(name: string, email: string) { this.name = name; ...

Fetching deeply nested data from JSON within Angular Material tables - ANGULAR

Having trouble retrieving data from localhost, especially when it's in a different structure. Any suggestions on how to properly extract and display this data for the user? This is my attempted approach, but I'm encountering an error message: ER ...

Guide on conducting unit tests for the provided code in Angular 8

I am currently working on implementing unit testing for this specific code snippet. applyFilter(filterValue: string) { this.dataSource.filter = filterValue.trim().toLowerCase(); this.DMDataSource.filter = filterValue.trim().toLowerCase(); // con ...