尝试关闭时出现 NgbModal 错误

NgbModal error when trying to close

我已经成功地将 NgbModal 集成到我的 Angular 2 应用程序中,我目前在模态中显示了另一个组件。

我遇到的问题是一旦它出现并单击关闭我收到以下错误消息:

Cannot read property 'close' of undefined

现在我一直在关注 Components as content 我查看了 HTML 并且还浏览了 Typescript,但是我不确定我在这里真正遗漏了什么。

这是我的类型脚本文件:

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { BugService } from '../service/bug.service';
import { Bug } from '../model/bug';
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { BugDetailComponent } from '../../bug-detail/bug-detail.component';

@Component({
   selector: 'bug-list',
   templateUrl: './bug-list.component.html',
   styleUrls: ['./bug-list.component.css']
})

export class BugListComponent implements OnInit {

  private bugs: Bug[] = [];

  constructor(private bugService: BugService, private cdRef: ChangeDetectorRef, private modalService: NgbModal) { }

  ngOnInit() {
    this.getAddedBugs();
  }

  getAddedBugs() {
    this.bugService.getAddedBugs().subscribe(bug => {
        this.bugs.push(bug);
        this.cdRef.detectChanges();
    },
        err => {
            console.error("unable to get added bug - ", err);
        });
  }

  open() {
     const modalRef = this.modalService.open(BugDetailComponent);
     modalRef.componentInstance.name = 'World';
  }
}

我导入 BugDetailComponent 然后在 open() 函数中引用它。当我在模式出现后单击关闭时,我看到了错误消息。

我的HTML如下:

<div class="modal-header" [id]="modalId">
<button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
    <span aria-hidden="true">&times;</span>
  </button>
<h4 class="modal-title">Hi there!</h4>
</div>
<div class="modal-body">
  <p>Hello, {{name}}!</p>
</div>
<div class="modal-footer">
   <button type="button" class="btn btn-secondary" (click)="activeModal.close('Close click')">Close</button>
</div>

有人可以解释一下为什么我会收到此错误并帮助我修复它吗?

请忽略,我解决了这个问题。 bug-detail.component.ts

中缺少以下构造函数
constructor(public activeModal: NgbActiveModal) {}

在您的 module.it 的提供者 [NgbActiveModal] 中添加 NgbActiveModal 将在您模块的所有组件中可用,然后在您的组件的构造函数中声明其变量,如构造函数(私有 ngvActiveModal:NgbActiveModal);

如果行

中缺少导入"NgbModal",您可以运行进入同样的错误

import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

如果有人遇到同样的问题(我尝试了 Code Ratchet 的解决方案,但 运行 遇到了与 Adrita Sharma 相同的问题)。

const modalRef = this.modalService.open(BugDetailComponent); 

我能够通过在模板中使用 modalRef.close() 来使用 closedismiss

示例:

<button type="button" class="btn btn-secondary" (click)="modalRef.close('Close click')">Close</button>

您可以在文件中添加 app.module.ts : 提供商:[ NgbActiveModal ],