如何按材质在网格列表中使用ngfor

时间:2019-05-13 12:16:08

标签: angular grid material

我想用Angluar材质实现动态网格列表。但我有一些问题。

我的JSON数据如下:

[
    {
        "abc": "sdfgsdfgs",
        "test": "dfgdfgdfgdfg"
    },
    {
       "abc": "dfgsdfgsdfg",
        "test": "dfgfgfgfgr"
    },
    {
        "abc": "sdfgsdfgs",
        "test": "asdfstest"
    },
] 


在HTML中,我想使用ngFor循环此JSON数据并显示在网格列表中。

<mat-grid-list cols="2" rowHeight="7:1">
      <mat-grid-tile>
        <u>abc</u>
      </mat-grid-tile>
      <mat-grid-tile>
        <u>test</u>
      </mat-grid-tile>
      <ng-container *ngFor="let item of datas">
      <mat-grid-tile>
        {{ item.abc}}
        {{ item.test}}
      </mat-grid-tile>
      </ng-container>
    </mat-grid-list>

预期结果应如下所示:

abc               test
-------------------------------
sdfgsdfgs        dfgdfgdfgdfg
dfgsdfgsdfg      dfgfgfgfgr


````

How can I loop this? 

2 个答案:

答案 0 :(得分:1)

mat-grid-tile上添加循环。

<mat-grid-list cols="2" rowHeight="7:1">
  <mat-grid-tile>
    <u>abc</u>
  </mat-grid-tile>
  <mat-grid-tile>
    <u>test</u>
  </mat-grid-tile>
  <ng-container>
    <mat-grid-tile *ngFor="let item of datas">
      {{ item.abc}}
      {{ item.test}}
    </mat-grid-tile>
  </ng-container>
</mat-grid-list>

对于已编辑的问题:

<mat-grid-list cols="2" rowHeight="7:1">
    <mat-grid-tile>
        <u>abc</u>
    </mat-grid-tile>
    <mat-grid-tile>
        <u>test</u>
    </mat-grid-tile>
    <ng-container *ngFor="let item of datas">
        <mat-grid-tile>
            {{ item.abc}}
        </mat-grid-tile>
        <mat-grid-tile>
            {{ item.test}}
        </mat-grid-tile>
    </ng-container>
</mat-grid-list>

Stackblitz

答案 1 :(得分:0)

如果表头是动态的,但是对于数组的所有索引来说都是相同的,则需要执行以下操作

component.ts

get gridHeaders(): Array<string> {
    return Object.keys(this.datas[0]);
}

component.html

<mat-grid-list cols="2" rowHeight="7:1">
      <mat-grid-tile *ngFor="let head of gridHeaders">
        <u>{{ head }}</u>
      </mat-grid-tile>
      <mat-grid-tile *ngFor="let item of datas">
        {{ item.abc}}
        {{ item.test}}
      </mat-grid-tile>
    </mat-grid-list>