0

I'm trying to implement a modal with angular following this tutorial (https://ng-bootstrap.github.io/#/components/modal - section "Components as content"), but I want the component displayed in the modal to persist it's state once closed for the next time it's opened.

I've created a simple Plunker example: http://plnkr.co/edit/EJyZ6nF5WVAS9bvQycQe?p=preview

What I want to achieve is that a call to open() after a call to openA() will show the text "Hello, A!" but it's not keeping the state.

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 this minimum setup be created? ¿Or which angular documentation do you recomend to understand what's going on?

2 Answers 2

1

Every time a new modal is opened with a component as content, the said component will be re-created (and destroyed on modal close). In this sense you can't "persist" component instances.

What you should be doing instead is to keep around model (data) that is driving component's display and behaviour.

Sign up to request clarification or add additional context in comments.

1 Comment

The case is that the component contains another component that takes a lot of time to initialize itself before it's ready to be shown (very complex form), that's the reason I want to "persist" the component. ¿Could the modal be hidden until the component is ready at least? Thank you!
0

Open parent model with windowClass option

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

This will add a class "refererToParent" to your parent modal window. Before opening your ChildModal remove class "show" from your parent modal window. Open then your ChildModal without backdrop

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

Set a listener on childModalRef that will append class 'show' once your ChildModel is closed.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.