【问题标题】:*ngFor loop through an array of arrays Angular6*ngFor 循环遍历数组 Angular6
【发布时间】:2019-03-21 14:28:43
【问题描述】:

我有这样的数组,

[[{"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]"(未测试)但我认为你可以像这样访问你的嵌套数组。

标签: angular ngfor


【解决方案1】:

您可以使用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>

【讨论】:

    【解决方案2】:

    它不是数组数组,你有两个数组。如果您想迭代第一个,请使用索引为 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-17
      • 2017-06-12
      • 1970-01-01
      • 2021-09-08
      • 2018-08-26
      • 2018-07-02
      • 2018-05-11
      • 1970-01-01
      相关资源
      最近更新 更多