问题
I want to implement a dynamic grid list with Angluar material. but I have some problems.
My JSON data looks like this:
[
{
"abc": "sdfgsdfgs",
"test": "dfgdfgdfgdfg"
},
{
"abc": "dfgsdfgsdfg",
"test": "dfgfgfgfgr"
},
{
"abc": "sdfgsdfgs",
"test": "asdfstest"
},
]
And in the HTML I want to use ngFor
to loop this JSON data and to show in a gird 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}}
{{ item.test}}
</mat-grid-tile>
</ng-container>
</mat-grid-list>
the expected result should look like this:
abc test
-------------------------------
sdfgsdfgs dfgdfgdfgdfg
dfgsdfgsdfg dfgfgfgfgr
````
How can I loop this?
回答1:
Add the loop on 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>
For edited question:
<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
回答2:
If your table headers are dynamic but these are the same for all indexes of your array you need to do the following
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>
来源:https://stackoverflow.com/questions/56112167/how-to-use-ngfor-in-grid-list-by-material