通过单击背景或模态外部停止关闭模态

stop closing the modal by clicking backdrop or outside the modal

我在我们的代码中使用了一个 angular2 ng-bootstrap 模态。

我希望当我在模态框外点击时模态框不会关闭。当前,在外部单击时模态正在关闭。

在 angular1 中,我曾经通过 [keyboard]="false" [backdrop]="'static'" 来做到这一点。但这是它在 angular2 中不起作用的时候了。

这是我的plunker

我的打开方式如下:

  open() {
    const modalRef = this.modalService.open(NgbdModalContent);
    modalRef.componentInstance.name = 'World';
  }
$modal.open({
   // ... other options
   backdrop  : 'static',
   keyboard  : false
});

创建模式时,您可以指定其行为:

根据@anshuVersatile 的回答,我知道我们需要使用一些模态选项。

然后我创建了一个 NgbModalOptions 的对象并将其作为我的 open 方法的第二个参数传递并且它起作用了。

代码如下:

let ngbModalOptions: NgbModalOptions = {
      backdrop : 'static',
      keyboard : false
};
console.log(ngbModalOptions);
const modalRef = this.modalService.open(NgbdModalContent, ngbModalOptions);

这是更新后的 plunker

虽然已经晚了,但它可能对其他面临问题的人有所帮助:

 const config: ModalOptions = {
                backdrop: 'static',
                keyboard: false,
                animated: true,
                ignoreBackdropClick: true,
                initialState: {
                  data1: 'new-user',
                  username: 'test'
                }
              };
              this.bsModalRef = this.modalService.show(MyComponent, config);

initialState 对象用于向模态传递数据。

如果 ngx-bootstrap/modal in angular 2+ (bsmodal) 使用 [config]="{ backdrop: 'static' }", .ts 文件如

import {ModalDirective} from 'ngx-bootstrap/modal';
@ViewChild('myModal') public myModal: ModalDirective;

 openpopup(){
     this.myModal.show()
  }

和.html喜欢

<button class="btn btn-md btn-pill btn-success mb-3 pull-right" type="button" data-toggle="modal" (click)="openpopup()">Open</button>

 <div bsModal #myModal="bs-modal" class="modal fade"  [config]="{ backdrop: 'static' }"  tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">Popup heading</h4>
          <button type="button" class="close" (click)="myModal.hide()" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>

        <div class="modal-body">
          <!---- popup content here---->
        </div>
      </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
  </div><!-- /.modal -->

在您的 component.ts 文件中

import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
import { ViewChild, TemplateRef } from '@angular/core';

//--------

constructor(
    private modalService: BsModalService
  ) {}

@ViewChild('sampleModal', {static: true}) sampleModalRef: TemplateRef<any>;

modalRef: BsModalRef;

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

//-------

open() {
    this.modalRef = this.modalService.show(this.sampleModalRef, this.config);
  }

HTML

<ng-template #sampleModal>
      .
      .
      .
      .
</ng-template>