我已成功将NgbModal集成到我的Angular 2应用程序中,我目前在模态中显示了另一个组件 .
我遇到的问题是,一旦它出现,我点击关闭我收到以下错误消息:
Cannot read property 'close' of undefined
现在我一直在关注Components as content我不确定我在这里真正想念的是什么 .
这是我的类型脚本文件:
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">×</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>
有人可以说明为什么我收到此错误并可能帮助我修复它?
4 回答
请忽略,我解决了这个问题 . 关闭了
bug-detail.component.ts
的以下构造函数如果有人遇到同样的问题(我试过Code Ratchet的解决方案,但遇到与Adrita Sharma相同的问题) .
通过在模板中使用modalRef.close(),我能够使用
close
和dismiss
.例:
在app模块的provider [NgbActiveModal]中添加NgbActiveModal . 然后它将在你的所有组件中都可用 . 然后在你的组件的构造函数中声明它的变量,如构造函数(private ngvActiveModal:NgbActiveModal);
如果导入“NgbModal”缺失,则可能会遇到相同的错误
import { NgbModal, NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';