首页 > 解决方案 > 在 ngfor 之外使用计数器

问题描述

我正在尝试在 ngFor 指令之外使用它来计算表中的行数,如下代码所示

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">IP</th>
      <th scope="col">Session_ID</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor='let obj of methodResponse; let theIndex = index;'>
      <th scope="row"> {{theIndex + 1}}</th>
      <td>{{obj.name}}</td>
      <td>{{obj.sourceIp}}</td>
      <td>{{obj.sessionId}}</td>
    </tr>
  <!-- I want to use the final value of theIndex value here -->
  </tbody>
</table>

如何计算每一行并在 ngFor 之外使用它,我试图在 ngFor 内部调用一个函数,但它对我不起作用,有什么帮助吗?

标签: angulartypescriptangularjs-directivengfor

解决方案


您可以使用length数组的属性来显示表格中有多少元素。

<table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Name</th>
      <th scope="col">IP</th>
      <th scope="col">Session_ID</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor='let obj of methodResponse; let theIndex = index;'>
      <td scope="row"> {{theIndex + 1}}</td>
      <td>{{obj.name}}</td>
      <td>{{obj.sourceIp}}</td>
      <td>{{obj.sessionId}}</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td>{{methodResponse.length}}</td>
    </tr>
  </tfoot>
</table>

推荐阅读