Angular 2 ng-bootstrap 关闭模态框

17
我试图关闭通过open(content)函数展示给我的模态框,就像ng-bootstrap的文档中所展示的那样。网站上提到我可以从NgbActiveModal中调用close或dismiss。
因此,我在组件中引入了NgbActiveModal并尝试调用dismiss()或close()。但两者都无法正常工作。首先,dismiss()未定义(我导入NgbActiveModal时是否有误?)。当我调用close()时,它似乎想调用lib.dom.d.ts中的一些奇怪函数,这完全不是我想要的。因此,在我导入了NgbActiveModal之后,似乎我无法访问ng-bootstrap提供的close和dismiss。请注意,我可以正常显示模态框。
在示例中,模态框通过(click)="c('Close click')"关闭。我不知道这是从哪里来的。
那么...我该如何调用close()或dismiss()(哪个有效)以摆脱模态框呢?

modal dismiss

3个回答

35

答案可以在这里找到。遗憾的是,ng-bootstrap网站缺少很多信息 Cannot close ng-bootstrap Modal

在组件类内部。

  private modalRef: NgbModalRef;

  // Modal
  open(content) {
    this.modalRef = this.modalService.open(content);
    this.modalRef.result.then((result) => {
      this.closeResult = `Closed with: ${result}`;
    }, (reason) => {
      this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
    });
  }

  onSave() {
    this.modalRef.close();
  }

感谢您分享链接。即使访问过那个链接,如何使用close()或dismiss()关闭模态框仍然不清楚。如果您能分享一下您是如何解决这个问题的,我将不胜感激。谢谢。 - Devner
已更新并解决。 - user172902
1
如果content是一个entryComponent,你会怎么做? - teddybear
2
@user172902 你应该将这个标记为正确/接受的答案,因为这是正确的方法,并且非常难从噪音中过滤出这些信息。 - Stephen R. Smith
@teddybear 你可以像答案中那样使用从 this.modalService.open(content) 返回的值(即 modalRef)。另一个选项是将 modalRef 传递给 entryComponent。 - Shahar

4
  1. At your modal component you need to add the line :

    @ViewChild('exampleModal') public exampleModal:ModalDirective;
    
  2. At html modal you need to insert in the div root :

    #exampleModal="bs-modal"
    
  3. At your modal component :

    onSave(){
       this.exampleModal.hide();
    }
    

同时在组件中导入 ModelDirective,代码如下:import { ModalDirective } from 'ngx-bootstrap'; - Saravanan Sachi

0

我按照 ng-bootstrap 的文档使用 Angular 6。最终,我发现只需更改 原始示例 中的一行即可解决问题:

modal-options.html

<ng-template #content let-d="dismiss">
  <div class="modal-header">
    <h4 class="modal-title">Modal title</h4>
    <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <p>One fine body&hellip;</p>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-light" (click)="d('Close click')">Close</button>
  </div>
</ng-template>

我将let-modal更改为let-d="dismiss",并且还更改了以下两行代码:

  • (click)="d('Cross click')"
  • (click)="d('Close click')"

modal-options.ts

constructor(private modalService: NgbModal) {}

openLg(content) {
  this.modalService.open(content, { size: 'lg' });
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接