0

I want to get the same reference of BsModalRef inside a service. Is it possible ?

openModal() {
    this.bsModalRef = this.modalService.show(SomeComponent, {
      initialState: {
        title: 'Modal title',
        data: {},
      },
    });
    console.log(this.modalRef); // this gives the opened modal reference
    this.service.mimic(); // this return a new instance of the bsModalRef service.
  }

this is service.mimic

mimic() {
    console.log(this.bsModalRef);
  }
Sparrow
  • 11
  • 1
  • 6

1 Answers1

0

I guess you want to access the reference inside the service. Create a variable in the service and then assign the value like so. The variable in test service should be an array!

openModal() {
    this.bsModalRef = this.modalService.show(SomeComponent, {
      initialState: {
        title: 'Modal title',
        data: {},
      },
    });
    //using a test service
    this.testService.modalRefs.push(this.modalRef);
    console.log(this.modalRefs); // this gives the opened modal reference
    this.service.mimic(); // this return a new instance of the bsModalRef service.
  }

   closeModal() {
    this.modalService.hide();
    //using a test service
    this.testService.modalRefs.pop();
  }

The modalRef of testService can be accessed anywhere the service is used. When you close a previous modal, we can remove the last element inside the array, so that the last element in the array will always be the modal that is opened, please refine this approach to suit your needs!

Naren Murali
  • 19,250
  • 3
  • 27
  • 54
  • This is a valid solution. But for example if there is a modal on top of another modal. Then when second modal is opened it will set its reference inside service. But when it is closed the name in service will not be changed to first modal. So thats one drawback. I want to get reference of the current modal opened. – Sparrow Aug 16 '22 at 04:56