在 *ngIf 中加载动态组件 - createComponent 未定义

Load dynamic component within *ngIf - createComponent is undefined

我正在尝试在用户单击如下所示的按钮时将动态组件加载到我的视图中:

<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>,但我没有成功地让它工作。

Source:

另一个解决方案建议使用 ElementRef 并检查已更改的状态,但即使在 ngAfterViewInit.

中尝试检查它时,即使那样也始终未定义

Source:

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

这是因为 *ngIf 删除了 div 元素,而条件评估为 false,这意味着该子元素不存在于您的组件模板中。

您可以使用 [hidden] 而不是只隐藏 div 元素,以便您可以通过模板引用变量访问它。

<button (click)="showContent()">Show Panel</button>
<!--This starts as 'showPanel = false'-->
<div [hidden]="!showPanel">
    <ng-template #ref></ng-template>
</div>

按照 yurzui 的想法,下面是我将如何应用它们:

Here 是 StackBlitz 示例.

changeDetectorRef.detectChanges()

showContent () {
    this.showPanel = !this.showPanel;

   if (this.showPanel) {
      this.cdr.detectChanges();
      this.loadComponent();
    }
  }

setter 对于 ViewChild

  private _ref: ViewContainerRef;

  private get ref () {
    return this._ref;
  }

  @ViewChild('ref', { static: false, read: ViewContainerRef })
  private set ref (r) {
    console.log('setting ref', r)
    this._ref = r;

    if (this._ref) {
      this.loadComponent();
    }
  }

  showPanel = false;

  constructor (
    private cdr: ChangeDetectorRef,
    private cfr: ComponentFactoryResolver,
  ) { }

  loadComponent () {
    const factory = this.cfr.resolveComponentFactory(ChildComponent);
    const component = this.ref.createComponent(factory);
  }

  showContent () {
    this.showPanel = !this.showPanel;
  }

使用<ng-container>

正如您所指出的,使用 ngTemplateOutlet 通常是一个很好的解决方案,但是当您处理多个组件时,在模板中执行所有这些逻辑会变得很麻烦。

我们可以利用 ViewContainerRef's API 来处理您的组件 (.ts file) 中的所有内容。

<button (click)="showContent()">Show Panel</button>

<ng-container #vcr></ng-container>
@ViewChild('vcr', { static: true, read: ViewContainerRef })
 vcr: ViewContainerRef;

 showContent () {
  this.showPanel = !this.showPanel;  

  this.showPanel && this.attachComponent();

  !this.showPanel && this.removeComponent();  
}

private attachComponent () {
  const compFactory = this.cfr.resolveComponentFactory(ChildComponent);

  const compView = this.vcr.createComponent(compFactory);
}

private removeComponent () {
    this.vcr.clear();
}

这种方法给了你更多的控制权!
例如,您可以通过使用 vcr.detachvcr.insert.

showPanel 变为 false 后保留组件的状态

You can find how right here.