Angular 动态组件:@ViewChildren 为 QueryList 中的每个组件获取 ViewContainerRef

CAl*_*lex 6 angular angular-dynamic-components

我正在构建一个带有动态选项卡的对话框,该对话框可以接收要放置在选项卡主体中的组件。我很难使用 @ViewChildren 创建多个动态组件。我过去已经很容易地使用单个组件和 @ViewChild 成功地完成了此操作。

这是我的模板:

<mat-tab *ngFor="let tab of tabs" [label]="tab.label">
     <ng-template #comp></ng-template>
</mat-tab>
Run Code Online (Sandbox Code Playgroud)

这是我的组件逻辑:

@ViewChildren("comp") dynComponents: QueryList<any>;


public ngAfterContentInit() {
  this.tabs.forEach(tab => {
     const factory = this._resolver.resolveComponentFactory(tab.component);
     console.log(this.dynComponents); // Returns undefined.

     // this.componentRef = this.vcRef.createComponent(factory);
  });
}
Run Code Online (Sandbox Code Playgroud)

即使在模板中对组件进行硬编码,我的 dynComponents 也未定义。我似乎需要从这个 dynComponents QueryList 获取 ViewContainerRef,但我不确定为什么它根本没有填充。我用这篇文章作为参考:帖子

Chr*_*ert 9

组件@ViewChildren中的 不起作用,因为它缺少read指示 的元数据属性ViewContainerRef

成分

import {
  AfterContentInit, Component, ComponentFactoryResolver, QueryList, Type, ViewChildren, ViewContainerRef
} from '@angular/core';


@Component({
  selector: 'dynamic-dialog',
  templateUrl: './dynamic-dialog.component.html',
  styleUrls: ['./dynamic-dialog.component.scss']
})
export class DynamicDialogComponent implements AfterContentInit {
  @ViewChildren('comp', { read: ViewContainerRef })
  public dynComponents: QueryList<ViewContainerRef>;

  public tabs = [];

  constructor(private _resolver: ComponentFactoryResolver) {}

  ngAfterContentInit() {
    this.dynComponents.map(
      (vcr: ViewContainerRef, index: number) => {
        const factory = this._resolver.resolveComponentFactory(
          this.tabs[index].component);
        vcr.createComponent(factory);
      }
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

ps 动态内容可以使用生命周期钩子AfterContentInitAfterViewInit.

  • 这按预期工作。很好的解决方案!任何将来查看这篇文章的人,请确保在创建它们时存储您的比较引用并在 ngOnDestroy 上销毁它们! (2认同)