Accessing ngx-bootstrap modals outside click event

Tags: , , ,



I’m calling ngx-bootstraps modal from within a ng-template in my applications component. I have built my current setup in a stackBlitz example

As you can see, I have added another event to the modals cancel/close button – when these are clicked two events fire. One to close the modal and another to do “something else”.

I want to be able to apply this “something else” to the ‘backdrop’ event that gets fired when clicking outside the modal. By default the modal closes when clicking the backdrop (this.modalRef.hide();). There is config to remove the close behaviour (ignoreBackdropClick) but that’s not what I am after here. I want to be able to keep the default behaviour and add another function like with the other triggers on the modal.

So I need to be able to “access” the backdrop event to apply a function to it – there is no html handle where I can do this.

StackBlitz example

component.html

<ng-template #printTemplate>
    <div class="modal-header">
        <h4>Title</h4>
        <button type="button" class="close pull-right" aria-label="Close" (click)="cancel(); anotherFunc()">
            <span aria-hidden="true" class="red">&times;</span>
        </button>
    </div>
    <div class="modal-body">
        <app-some></app-some>
    </div>
    <div class="modal-footer d-block">
        <button class="btn btn-secondary float-right mr-4" (click)="cancel(); anotherFunc()">Cancel</button>
    </div>
</ng-template>

component.ts

  openModal(printTemplate: TemplateRef<any>) {
    this.modalRef = this.modalService.show(printTemplate);
  }

  cancel() {
    this.modalRef.hide();
  }

  anotherFunc() {
    console.log("func triggered");
  }

Answer

To achieve what your asking for you can read the event backdrop-click once modal is showing and you click backdrop. Here’s a working fork.

config = {
  backdrop: true,
  ignoreBackdropClick: false
};

openModal(printTemplate: TemplateRef<any>) {
  this.modalRef = this.modalService.show(printTemplate, this.config);
  this.modalRef.onHide.subscribe((reason: string | any) => {
    if(reason === 'backdrop-click') {
      this.myFunc(); // run your function here
    }
  });
};

Note: Tested on ngx-bootstrap 6.1.0, typings seems broken below versions but probably fixable by changing the typings.



Source: stackoverflow