You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PrimeNG p-table循环中获取元素索引以判断是否为末尾元素

解决方案

PrimeNG p-table的body模板内置了多个上下文变量,不需要手动写*ngFor就可以直接获取索引、是否为首行/末行等信息:

  • 通过let-rowIndex="rowIndex"声明变量,可获取当前行对应你绑定的histories数组的全局下标
  • 通过let-isPageLast="last"声明变量,可直接判断当前行是否为当前分页的最后一行
  • 如果要判断是否为整个histories列表的最后一行,直接比对索引和数组总长度即可:rowIndex === histories.length - 1

修改后的示例代码如下:

<p-table  [paginator]="true" [rows]="10" [showCurrentPageReport]="true"
          currentPageReportTemplate="Showing {first} to {last} of {totalRecords} entries" [rowsPerPageOptions]="[10,25,50]"
          [value]="histories">
  <ng-template pTemplate="header">
    <tr>
      <th>duration</th>
      <th>build id</th>
      <th>操作</th>
    </tr>
  </ng-template>
  <!-- 新增行索引、末行标识的变量声明 -->
  <ng-template pTemplate="body" let-build let-rowIndex="rowIndex" let-isPageLast="last">
    <tr>
      <td [style]="{'word-wrap':'break-word !important'}">
        {{ secondsToDhms(build.duration) }}
      </td>
      <td [style]="{'word-wrap':'break-word !important'}">
        {{ build.build_id }}
      </td>
      <td>
        <!-- 示例:不是整个列表最后一行时才显示删除按钮 -->
        <p-button *ngIf="rowIndex !== histories.length - 1" icon="pi pi-trash" styleClass="p-button-text"></p-button>
        <!-- 示例:不是当前分页最后一行时才显示下移按钮 -->
        <p-button *ngIf="!isPageLast" icon="pi pi-chevron-down" styleClass="p-button-text"></p-button>
      </td>
    </tr>
  </ng-template>
  <ng-template pTemplate="paginatorleft">
    <p-button type="button" icon="pi pi-plus" styleClass="p-button-text"></p-button>
  </ng-template>
  <ng-template pTemplate="paginatorright">
    <p-button type="button" icon="pi pi-cloud" styleClass="p-button-text"></p-button>
  </ng-template>
</p-table>

内容的提问来源于stack exchange,提问作者Youssef Boudaya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 06:54:03