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

Angular表格行点击实现数量增减功能求助

解决方案

你只需要将两个点击事件的逻辑合并到一个方法中,根据行的选中状态来决定是添加还是减去对应数量,具体修改如下:

修改TypeScript代码

替换原来的total和cambiarFlag方法,新增一个合并逻辑的方法:

export class EntryOrderLinesComponent implements OnInit {
  totalCantidad: number = 0;

  articulos = [
    {
      articulo: '385/65X22.5 HANKOOK AH51 160K (3003836)',
      cantidad: 94,
      recogida: '0',
      selected: false,
    },
    {
      articulo: '385/65X22.5 HANKOOK TH31 164K (3003309)',
      cantidad: 60,
      recogida: '0',
      selected: false,
    },
  ];

  toggleItemSelection(item: any) {
    // 切换选中状态
    item.selected = !item.selected;
    // 根据选中状态更新总数量
    if (item.selected) {
      this.totalCantidad += item.cantidad;
    } else {
      this.totalCantidad -= item.cantidad;
    }
  }
}

修改HTML代码

将<tr>标签上的两个(click)事件合并为一个,调用新的方法:

<tbody>
    <tr *ngFor="let item of articulos; index as i" (click)="toggleItemSelection(item)" 
        [ngClass]="{'seleccionada': item.selected, 'noSeleccionada': !item.selected}">
        <td>{{item.articulo}}</td>
        <td>{{item.cantidad}}</td>
        <td>{{item.recogida}}</td>
    </tr>
    <br>
</tbody>

<div type="button" class="col border border-white border-4" id="other" type="button"
    routerLink="/entry-order-lines-quantity" style="background-color:rgb(3, 71, 150);">
    Cantidad {{totalCantidad}}
</div>

逻辑说明

点击行时,先切换该行的selected状态,然后根据新的状态判断:

  • 如果变为选中状态,就把该行的cantidad加到totalCantidad中
  • 如果变为未选中状态,就从totalCantidad中减去该行的cantidad

这样就实现了点击添加、再次点击减去数量的需求,同时保留了选中行变色的功能。

内容的提问来源于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 02:50:28