sammani anuththara
sammani anuththara

Reputation: 145

*ngFor loop through an array of arrays Angular6

I have array like this,

[[{"user":"1","nice":"0","sys":"1","CPU":"93","irq":"0"}, 
{"user":"1","nice":"0","sys":"1","CPU":"92","irq":"0"}, 
{"user":"1","nice":"0","sys":"1","CPU":"92","irq":"0"}, 
{"user":"1","nice":"0","sys":"1","CPU":"92","irq":"0"}], 
[{"user":"0","nice":"0","sys":"0","CPU":"91","irq":"0"}, 
{"user":"0","nice":"0","sys":"1","CPU":"91","irq":"0"}, 
{"user":"1","nice":"0","sys":"0","CPU":"91","irq":"0"}, 
{"user":"0","nice":"0","sys":"0","CPU":"90","irq":"0"}]]

I want to loop through this array of object in an HTML table using ngFor

<table class="table table-striped mt-5">
  <thead>
    <tr>
      <th scope="col">User</th>
      <th scope="col">Nice</th>
      <th scope="col">Sys</th>
      <th scope="col">CPU</th>
      <th scope="col">IRQ</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let post of posts">
      <td>{{post.user}}</td>
      <td>{{post.nice}}</td>
      <td>{{post.sys}}</td>
      <td>{{post.CPU}}</td>
      <td>{{post.irq}}</td>
    </tr>
  </tbody>
</table>

But my code doesn't work

Upvotes: 3

Views: 3234

Answers (2)

Doguita
Doguita

Reputation: 15703

You can use ng-container to hold one ngFor and do the second ngFor in the tr tag like this:

<tbody>
    <ng-container *ngFor="let group of posts">
        <tr *ngFor="let post of group">
            <td>{{post.user}}</td>
            <td>{{post.nice}}</td>
            <td>{{post.sys}}</td>
            <td>{{post.CPU}}</td>
            <td>{{post.irq}}</td>
        </tr>
    </ng-container>
</tbody>

Upvotes: 5

Sajeetharan
Sajeetharan

Reputation: 222522

Its not array of arrays, you have two arrays. if you want to iterate over the first one use the index as posts[0]

 <tr *ngFor="let post of posts[0]">
      <td>{{post.user}}</td>
      <td>{{post.nice}}</td>
      <td>{{post.sys}}</td>
      <td>{{post.CPU}}</td>
      <td>{{post.irq}}</td>
  </tr>

STACBKLITZ DEMO

Upvotes: 4

Related Questions