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

Angular实现表格多行选中并计算数量列总和显示到div

实现表格多行选中并求和的解决方案

步骤1:修改TypeScript代码

添加选中项数组,实现选中状态切换和总和计算逻辑:

// 存储选中的行数据
selectedItems: any[] = [];

// 切换行的选中状态
toggleSelection(item: any) {
  // 确保cantidad转为数字类型
  item.cantidad = +item.cantidad;
  
  const existIndex = this.selectedItems.indexOf(item);
  if (existIndex > -1) {
    // 已选中则移除
    this.selectedItems.splice(existIndex, 1);
  } else {
    // 未选中则添加
    this.selectedItems.push(item);
  }
}

// 实时计算选中项的cantidad总和
get totalCantidad(): number {
  return this.selectedItems.reduce((sum, item) => sum + item.cantidad, 0);
}

步骤2:修改HTML代码

更新表格行的点击事件,添加选中状态标识,并显示总和:

<!-- 表格区域 -->
<table>
  <tr *ngFor="let item of articulos" 
      (click)="toggleSelection(item)"
      [class.selected]="selectedItems.includes(item)">
      <td>{{item.articulo}}</td>
      <td>{{item.cantidad}}</td>
      <td>{{item.recogida}}</td>
  </tr>
</table>

<!-- 显示总和的容器 -->
<div>选中行数量总和: {{ totalCantidad }}</div>

可选:添加选中行样式(CSS)

为了直观区分选中状态,可添加以下样式:

tr.selected {
  background-color: #f0f0f0;
}

功能说明

  • 点击任意表格行即可切换该行的选中状态
  • 选中的行自动纳入求和计算,取消选中则从总和中剔除
  • 总和会根据选中状态实时更新并展示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:50:22