首页 > 解决方案 > Angular 9:创建动态 ViewContainerRef 以循环组件数组

问题描述

我正在尝试使用具有不同组件的 angular2gridster 创建仪表板卡网格页面作为每张卡的内容。卡片是在指定卡片数据的对象数组上使用 NgFor 创建的,包括包含组件的属性(如下所示)。不知何故,一个错误显示在 ViewContainerRef 是如何未定义的,尽管如果我将模板移出 NgFor 范围是很好的。

{
      component: CashflowOverviewComponent,
      title: 'example title',
      visible: true,
      metadata: {
        //XY coordinate in grid
        x: 0,
        y: 0,
        //Width and height
        w: 2,
        h: 1,
      },
    },

在我的 HTML 中,我尝试使用 NgFor 生成代码

<div *ngFor="let widget of widgets">
        <ngx-gridster-item *ngIf="widget.visible" class="grid_card" [(x)]="widget['metadata'].x "
            [(y)]="widget['metadata'].y" [(w)]="widget['metadata'].w" [(h)]="widget['metadata'].h">
            <div class="card">
                <div class="card_header">
                    <div *ngIf="dragEnabled" class="material-icons card_drag handler_icon drag_icon">drag_indicator
                    </div>
                    <div class="card_title">Card title</div>
                </div>
                <ng-template #cardContent></ng-template>
                {{dynamicComponentGenerator(widget.component)}}
                <div class="card_content">
                </div>
            </div>
        </ngx-gridster-item>
    </div>

下面的代码是我如何尝试初始化

 @ViewChild("cardContent",{static:true , read: ViewContainerRef}) cardContent: ViewContainerRef;QueryList<ViewContainerRef>;

这是我用来尝试让组件显示的功能

dynamicComponentGenerator  = (component)=>{
    let factory = this.r.resolveComponentFactory(component);
    this.cardContent.clear();
    let compRef = this.cardContent.createComponent(factory);
  }

标签: angulartypescriptangular9

解决方案


推荐阅读