我想用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?
答案 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>
答案 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>