首页 > 解决方案 > 在 *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>,但我没有成功让它工作。

来源:在 ngAfterViewInit 中调用 ViewContainerRef 时未定义

另一种解决方案建议使用ElementRef并检查 chaged 状态,但即使在尝试检查时始终未定义ngAfterViewInit

来源:*ngIf 中的@ViewChild

我正在寻找适用于 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.
}

标签: angularangular8angular-ng-if

解决方案


这是因为 *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>

推荐阅读