How to use ngfor in grid-list by material

你。 提交于 2021-01-27 04:40:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!