【发布时间】:2021-11-21 00:15:44
【问题描述】:
在 *ngFor 循环内呈现的项目中调用 NgbModal open() 时遇到问题。
我有一个要显示的项目列表。在上述项目的click 上,我希望打开一个模式以提示用户提供一些其他信息。
单击项目时,我可以看到元素通过 DevTools 添加到 DOM,但模式没有添加 show 类。应该呈现为模态内容的组件也未正确初始化。如果我手动添加show 类,我可以看到模态的内容,但组件不能正常工作。
重要的是要注意,为了测试,我添加了一个订阅点击事件的按钮,它将一个假项目传递给相同的函数setSelected()。这种打开模式的方法没有问题。该问题仅在*ngFor 内出现。
我有一个console.log 在ConnectionModalComponent(作为模态的内容传递)构造函数中,另一个是ngAfterViewInit。当通过*ngFor 之外的按钮激活模式时,我在控制台中看到了两个日志语句,但是当从*ngFor 中激活模式时,我只看到构造函数的日志语句,而不是后者。
我正在使用@angular/core@12.1.2 & @ng-bootstrap/ng-bootstrap@10.0.0。
testComponent.html.ts - 具有 *ngFor 的组件
<div>
<div
*ngFor="let item of items"
(click)="setSelected(item)"
>
<span class="full-height">
<div class="card-body">
<div class="card-title">
{{ item.nickname }}
</div>
</div>
</span>
</div>
</div>
testComponent.component.ts - 从 HTML 模板调用的函数。
public setSelected(item: ItemViewModel): void {
this.testAlertService.open();
}
testAlert.service.ts - 从组件调用以打开 NgbModal 的服务。
import { Injectable } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { ConnectionModalComponent } from '../../components/shared';
@Injectable()
export class TestAlertService {
constructor(private modalService: NgbModal) {}
open() {
this.modalService.open(ConnectionModalComponent, { ariaLabelledBy: 'modal-basic-title' }).result.then(
(result) => {
console.log(`Closed with: ${result}`);
},
(reason) => {
console.log(`Dismissed ${this.getDismissReason(reason)}`);
}
);
}
private getDismissReason(reason: any): string {
if (reason === ModalDismissReasons.ESC) {
return 'by pressing ESC';
} else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
return 'by clicking on a backdrop';
} else {
return `with: ${reason}`;
}
}
}
【问题讨论】:
标签: angular typescript ngfor ng-bootstrap ng-bootstrap-modal