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

如何通过输入框事件传递获取Mat Table的行索引?

Mat Table 事件同步传递行索引实现

你可以直接通过matCellDef导出的上下文变量拿到当前行索引,随事件参数一起传入处理函数即可。

模板代码调整

*matCellDef和Angular内置的*ngFor微语法规则一致,支持直接声明当前渲染行的索引变量,在绑定keyup、change事件时把这个变量作为参数传入:

<!-- Contribution Percentage列定义 -->
<ng-container matColumnDef="contributionPercentage">
  <th mat-header-cell *matHeaderCellDef>Contribution Percentage (%)</th>
  <td mat-cell *matCellDef="let item; let idx = index">
    <input
      type="number"
      min="0"
      max="100"
      (keyup)="onPercentageChange($event, idx)"
      (change)="onPercentageChange($event, idx)"
    >
  </td>
</ng-container>

注意:这里获取到的idx是表格当前渲染视图的行索引,如果表格开启了分页、排序、筛选功能,这个索引会随渲染结果变化,和原始数据源的数组索引不匹配。

组件TS代码调整

修改事件处理函数的形参,接收传入的行索引即可使用:

onPercentageChange(event: Event, rowIndex: number): void {
  // 拿到输入框的值
  const percentage = Number((event.target as HTMLInputElement).value);
  // 可直接通过rowIndex访问渲染数据对应行
  console.log('当前行索引:', rowIndex, '输入百分比:', percentage);
}

分页/排序场景的稳妥写法

如果表格接入了分页、排序能力,不建议直接使用视图索引,避免索引错位。更可靠的方式是直接传入当前行的完整数据对象,通过唯一主键匹配原始数据位置:

<td mat-cell *matCellDef="let item">
  <input
    type="number"
    min="0"
    max="100"
    (keyup)="onPercentageChange($event, item)"
    (change)="onPercentageChange($event, item)"
  >
</td>
onPercentageChange(event: Event, rowData: ContributionItem): void {
  const percentage = Number((event.target as HTMLInputElement).value);
  // 需要原始索引时通过唯一id匹配,不受排序/分页影响
  const realIndex = this.dataSource.data.findIndex(i => i.id === rowData.id);
  // 直接修改rowData对象也能同步更新表格渲染
  rowData.contributionPercentage = percentage;
}

内容的提问来源于stack exchange,提问作者vd sanduni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 05:06:48