【发布时间】:2020-02-27 00:35:41
【问题描述】:
当用户单击如下所示的按钮时,我正在尝试将动态组件加载到我的视图中:
<button (click)="showContent()">Show Panel</button>
<!--This starts as 'showPanel = false'-->
<div *ngIf="showPanel">
<ng-template #ref></ng-template>
</div>
但是,当单击视图中的按钮时,我尝试运行 loadComponent(),但收到一条错误消息,指出 Cannot read property 'createComponent' of undefined
我已经查找了一些解决方案,有人建议使用QueryList<ViewContainerRef>,但我没有成功地让它工作。
来源:ViewContainerRef is undefined when called in ngAfterViewInit
另一个解决方案建议使用 ElementRef 并检查 chaged 状态,但即使在尝试在 ngAfterViewInit 中检查它时也始终未定义。
我正在寻找适用于 Angular 8 的选项,但我不完全确定下一步该去哪里。
代码如下:
parent.component.ts
export class ParentComponent {
@ViewChild('ref', { static: false, read: ViewContainerRef }) ref: ViewContainerRef;
showPanel = false;
loadComponent(): void {
const factory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
const component = this.ref.createComponent(factory);
component.changeDetectorRef.detectChanges();
}
showContent(): void {
this.showPanel = !this.showPanel;
this.loadContent(); // Error is thrown here, this doesn't make sense as *ngIf should now be true.
}
【问题讨论】:
-
我不明白你想如何将组件加载到自
showPanel = false;以来尚不存在的 ref 中 -
您的 DOM 元素不存在,因为您在 showPanel 上以
false开头,因此您的 ref 不存在。 -
@yurzui,我知道,但是当您单击按钮并运行 loadContent() 时,它会失败并出现相同的错误。我的问题不是很清楚。已更新。
-
@Michelangelo 和上面的 Yurzui 一样,我的问题不是很清楚我已经更新它以显示实际发生的事情
-
在您更改 showPanel 属性时,Angular 不会更新视图。您可以在此处使用许多选项:1)对 ViewChild 使用 setter 2)使用 ngComponentOutlet 渲染组件 3)在
this.showPanel = !this.showPanel;之后使用 cdRef.detectChanges()
标签: angular angular8 angular-ng-if