3

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

1
  • Try *ngFor="let post of posts[0]" (not tested) but I think you can access to your nested array like this. Commented Oct 17, 2018 at 1:04

2 Answers 2

5

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>
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

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.