Vaibhav
Vaibhav

Reputation: 821

Iterating over array in angular2

enter image description hereHi I want to iterate over following array using angular2

let list = [{"-1" : [{a : 1, b: 2, c: 2}, {a:3, b: 4, c: 2}]},
            {"0" : [{a : 12, b: 32, c: 22}, {a:31, b: 24, c: 32}}]

And show the out put in a table formate as shown in the image

please help me in solving the problem.

Following code i have tried

<table >
<thead>
  <tr>
    <th > a </th>
    <th > b </th>
    <th > c </th>
  </tr>
</thead>
<tbody >
  <tr *ngFor="let element of list">
           <td> {{element['-1'].a}}</td>
           <td> {{element['-1'].b}}</td>
           <td> {{element['-1'].c}}</td>
  </tr>
 </tbody>
 </table> 

But i am not able to add the row "-1", "0"

Upvotes: 0

Views: 842

Answers (1)

dfsq
dfsq

Reputation: 193271

It's better if you reformatted data a little bit:

let list = [
  {"-1" : [{a : 1, b: 2, c: 2}, {a:3, b: 4, c: 2}]},
  {"0" : [{a : 12, b: 32, c: 22}, {a:31, b: 24, c: 32}}
]

this.list = list.map(item => {
  const keys = Object.keys(item)
  return {
    header: keys[0],
    data: item[keys[0]]
  }
})

Then you will need to render it with two loops. Maybe like this:

<table>
  <thead>
    <tr>
      <th>a</th>
      <th>b</th>
      <th>c</th>
    </tr>
  </thead>
  <ng-template ngFor let-item [ngForOf]="list">
    <tbody>
      <tr class="header">
        <td colspan="3">{{ item.header }}</td>
      </tr>
      <tr *ngFor="let row of item.data">
        <td>{{ row.a }}</td>
        <td>{{ row.b }}</td>
        <td>{{ row.c }}</td>
      </tr>
    </tbody>
  </ng-template>
</table>

Demo: http://plnkr.co/edit/Q0HAIFO8YAW5EUDJ5p2g?p=preview

Upvotes: 2

Related Questions