在点击事件之外访问 ngx-bootstrap 模态

Accessing ngx-bootstrap modals outside click event

我打电话给ngx-bootstraps modal from within a ng-template in my applications component. I have built my current setup in a stackBlitz example

如您所见,我向模态 cancel/close 按钮添加了另一个事件 - 单击这些按钮时会触发两个事件。一个用于关闭模式,另一个用于执行“其他操作”。

我希望能够将此“其他内容”应用到 'backdrop' 事件,该事件在单击模式外部时被触发。默认情况下,单击背景时模式关闭 (this.modalRef.hide();)。有配置可以删除关闭行为(ignoreBackdropClick),但这不是我想要的。我希望能够保持默认行为并添加另一个功能,就像模态上的其他触发器一样。

所以我需要能够“访问”背景事件以对其应用函数 - 没有 html 可以执行此操作的句柄。

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

要实现您的要求,您可以阅读活动 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
    }
  });
};

注意: 在 ngx-bootstrap 6.1.0 上测试,打字似乎低于版本,但可能可以通过更改打字来修复。