简体   繁体   中英

Dynamic build a table from json data in angular2

I can't wrap my head around a looping system i need to make to build up a table from json data. This is what i've got so far (tried some other stuff but i think this illustrates it the best way).

Looping through the headers works fine, it's just the cells i can't get to work.

This is my dummy data:

    tableMockData = [
   {
     "header": "TH 1",
      "rows": [
          "TH1 - row1",
          "TH1 -row2",  
          "TH1 - row3", 
          "TH1 - row4" 
      ]
   },
   {
    "header": "TH 2",
     "rows": [
         "TH2 -row1",
         "TH2 - row2",   
         "TH2 - row3", 
         "TH2 - row4",
     ]
  },
  {
    "header": "TH 3",
     "rows": [
      "TH3 -row1",
      "TH3 - row2",  
      "TH3 - row3", 
      "TH3 - row4",
     ]
  },
  {
    "header": "TH 4",
     "rows": [
      "TH4 - row1",
      "TH4 - row2",  
      "TH4 - row3", 
      "TH4 - row4",
     ]
  }
]

This is my basic loop as starting point:

 <tr *ngFor="let row of tableMockData; let i = index">
      <td>{{row.rows[i]}}</td>
  </tr>

This is my outcome: 在此处输入图片说明

This is my desired outcome: 在此处输入图片说明

Can someone point me out in the right direction, i know wich cell needs to go where but i simply can't wrap my head around how to loop through it.

Thanks :)

Update: here is a stackblitz example: https://stackblitz.com/edit/angular-cdoqwb

Update your Html with below code

<table>
 <tr>
    <th  *ngFor="let row of tableMockData; let i = index">{{row.header}} 
   </th>
</tr>
<tr  *ngFor="let row of tableMockData; let i = index">
 <td *ngFor="let row1 of row.rows">
   {{row1}}
 </td>
</tr>
</table>

You do not properly bind your JSON.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM