angularngx-bootstrapangular12ngx-bootstrap-modal

How to get reference of a ngx-bootstrap modal in angular


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);
  }

Solution

  • 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!