Angular表格多行选择及Cantidad列数值求和实现求助
解决方案
1. 修改TypeScript组件代码
在组件类中添加选中项管理与总和计算逻辑:
export class EntryOrderLinesComponent implements OnInit { articulos = [ { "articulo": "385/65X22.5 HANKOOK AH51 160K (3003836)", "cantidad": "94", "recogida": "0", }, { "articulo": "385/65X22.5 HANKOOK TH31 164K (3003309)", "cantidad": "60", "recogida": "0", }, ]; datosEmpresaTaller: Observable<EmpresaTaller>; // 存储选中的行数据 selectedItems: any[] = []; constructor(private datosService: DatosService) { } ngOnInit(): void { this.datosEmpresaTaller = this.datosService.getEmpresaTaller(); } // 切换行的选中状态 toggleItemSelection(item: any): void { const index = this.selectedItems.indexOf(item); if (index > -1) { this.selectedItems.splice(index, 1); } else { this.selectedItems.push(item); } } // 实时计算选中行的Cantidad总和 get totalCantidad(): number { return this.selectedItems.reduce((sum, item) => { // 将字符串类型的cantidad转为数字后累加 return sum + parseInt(item.cantidad, 10); }, 0); } }
2. 修改HTML模板代码
添加选中交互、高亮样式,并展示计算后的总和:
<div class="container-fluid"> <div class="table-responsive"> <!-- 展示实时总和 --> <div class="mb-3"> <strong>总计 Cantidad: {{ totalCantidad }}</strong> </div> <table class="table table-striped" id="table" style="margin-top: 1%;"> <thead> <tr> <th scope="col">选择</th> <th scope="col">Artículo</th> <th scope="col">Cantidad</th> <th scope="col">Recogida</th> </tr> </thead> <tbody> <tr *ngFor="let item of articulos; let i=index" (click)="toggleItemSelection(item)" [class.table-active]="selectedItems.includes(item)" style="cursor: pointer;" > <td> <input type="checkbox" (change)="toggleItemSelection(item)" [checked]="selectedItems.includes(item)" > </td> <td>{{item.articulo}}</td> <td>{{item.cantidad}}</td> <td>{{item.recogida}}</td> </tr> </tbody> </table> <input type="button" name="OK" class="ok" value="OK"/> </div> </div>
关键细节说明
- 选中状态同步:点击行或复选框都能触发选中状态切换,
selectedItems数组统一维护选中数据。 - 视觉反馈:借助Bootstrap的
table-active类为选中行添加高亮样式,让用户直观看到选中状态。 - 实时求和:通过
reduce方法遍历选中项,将字符串类型的cantidad转为整数后累加,totalCantidadgetter会实时更新计算结果。
内容的提问来源于stack exchange,提问作者Miriam
相关产品推荐
相关产品推荐

