angular - 在 *ngIf 中加载动态组件 - createComponent 未定义
问题描述
当用户单击如下所示的按钮时,我正在尝试将动态组件加载到我的视图中:
<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>
,但我没有成功让它工作。
另一种解决方案建议使用ElementRef
并检查 chaged 状态,但即使在尝试检查时始终未定义ngAfterViewInit
。
我正在寻找适用于 Angular 8 的选项,但我不完全确定下一步该往哪里看。
下面的代码:
父组件.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.
}
解决方案
这是因为 *ngIf 在条件评估为 false 时删除了 div 元素,这意味着子元素不存在于您的组件模板中。
您可以使用 [hidden] 代替,它只隐藏 div 元素,以便您可以通过模板引用变量访问它。
<button (click)="showContent()">Show Panel</button>
<!--This starts as 'showPanel = false'-->
<div [hidden]="!showPanel">
<ng-template #ref></ng-template>
</div>
推荐阅读
- python - 将新列分配给现有 Datafram 时的空值
- sql - 我将如何将文本结果聚合到一个单一的临时列中?
- c++ - 更改入口点的目的是什么( main() 函数)
- python-3.x - python jupyter的vscode无法显示视频
- typescript - 在 vscode 上:'tsc' 不是内部或外部命令、可运行程序或批处理文件
- django - Django 3.0 - 多语言模型 - 如何为当前使用的语言制作 __str__ 返回值?
- javascript - 循环通过承诺和等待?
- google-cloud-platform - 如何将 cuda 驱动程序添加到 gcp Ubuntu vm?
- android - 如何让这个 BroadCastReceiver 工作?
- c - 如何在 C 中完全删除动态数组而不仅仅是单个元素