*ngFor循环遍历一个数组的数组 Angular6

3

我有一个像这样的数组:

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

我希望使用ngFor循环遍历这个对象数组,并在HTML表格中显示它。
<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>

但是我的代码没有运行


尝试使用 *ngFor="let post of posts[0]"(未测试),但我认为您可以像这样访问嵌套数组。 - ghuntheur
2个回答

5
您可以使用 ng-container 来容纳一个 ngFor,并在 tr 标签中执行第二个 ngFor,如下所示:
<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

这不是一个数组的数组,而是两个数组。如果你想遍历第一个数组,请使用索引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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接