Tengo una matriz como esta,

[[{"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"}]]

Quiero recorrer esta matriz de objetos en una tabla HTML usando 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>

Pero mi código no funciona

3
sammani anuththara 17 oct. 2018 a las 04:01

2 respuestas

La mejor respuesta

Puede utilizar ng-container para mantener uno ngFor y haga el segundo ngFor en la etiqueta tr de esta manera:

<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>
4
Doguita 17 oct. 2018 a las 01:31

No es una matriz de matrices, tienes dos matrices. si desea iterar sobre el primero, use el índice como 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

4
Sajeetharan 17 oct. 2018 a las 01:05