0

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"

3
  • Welcome to SO, please check how to ask a question: stackoverflow.com/help/how-to-ask What have you tried and where have you failed? Commented Jan 24, 2017 at 10:31
  • @ dfsq its a typo error please check now. Commented Jan 24, 2017 at 10:38
  • its an array inside an array. You are iterating only once. Commented Jan 24, 2017 at 11:09

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the solution it help a lot +1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.