创建动态组件不起作用

问题描述 投票:-1回答:3

在代码下创建动态组件但不渲染,它在空元素中显示。

app.components.ts

我的json:

comp =[  
   {  
      "ty":"screen",
      "grids":[  
         {  
            "ty":"grid",
            "components":[  
               {  
                  "ty":"tb"
               },
               {  
                  "ty":"tb"
               }
            ]
         },
         {  
            "ty":"grid",
            "components":[  
               {  
                  "ty":"bt"
               }
            ]
         }
      ]
   }
]

从json中迭代组件

ngOnInit() {
      // this.iterate(keys: any)
      var griditem;

      for(var i=0;i<this.comp[0].grids.length;i++)

      {
        if(this.comp[0].grids[i].ty=='grid'){
          griditem='<div> sample Grid';
              for(var j=0;j<this.comp[0].grids[i].components.length;j++)
              {
                if(this.comp[0].grids[i].components[j].ty=='tb'){
                  griditem = griditem +'<input matInput placeholder='Favorite food' value='Sushi'>';
                }else if(this.comp[0].grids[i].components[j].ty=='bt'){
                  griditem = griditem +'<div> sample Button'+j+' </div>';
                }
              }
              griditem= griditem +'</div>';              

        }
        this.renderedGrid = this.renderedGrid+griditem;
      }


}

在app.components.html中

<div [innerHTML]="renderedGrid"></div>

上面的代码没有渲染输入元素,它渲染空元素,此代码中缺少任何元素。

angular angular-material
3个回答
0
投票

如果我理解正确,这整个方法似乎是角度分量系统的反模式。但听起来问题确实如此:如何迭代模型以生成角度材料组件。

答案是ngFor,ngIf,这是你当前模型的一个例子

无需在打字稿中添加任何代码,而不是模型

在HTML中,您可以执行以下操作

<div *ngFor="let component of comp">
  <mat-grid-list cols="4" rowHeight="100px" *ngFor="let grid of component.grids">
    <mat-grid-tile *ngFor="let gridComponent of grid.components">
      <div *ngIf="gridComponent.ty=='tb'">
        <input matInput placeholder="Favorite food">
      </div>
      <div *ngIf="gridComponent.ty=='bt'">
        <button md-button>Click me!</button>
      </div>
    </mat-grid-tile>
  </mat-grid-list>
</div>

对于每个组件,我们可以使用ngFor创建mat-grid-list对于每个网格列表,我们可以使用ngFor创建一个组件,在每个组件内部我们可以使用ngIf识别我们想要添加的标签类型

enter image description here


0
投票

enter image description here

像这样创建了按钮组件和输入组件


0
投票
<div *ngFor="let component of comp">
  <mat-grid-list cols="4" rowHeight="100px" *ngFor="let grid of component.grids">
    <mat-grid-tile *ngFor="let gridComponent of grid.components">
      <div *ngIf="gridComponent.ty=='tb'">
       <input-comp></input-comp>
      </div>
      <div *ngIf="gridComponent.ty=='bt'">
       <button-comp></button-comp>
      </div>
    </mat-grid-tile>
  </mat-grid-list>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.