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

Angular TypeScript 12如何为表格循环内单个商品应用折扣函数

问题根因
  • 所有商品的输入框都双向绑定了组件全局的discount变量,任意输入框修改都会同步更新这个全局值,自然会影响所有商品的计算逻辑
  • 计算函数里的discounttotal、totalwithDiscount也都是全局变量,没有和单个商品绑定,无法单独存储每个商品的折扣结果
修改方案

1. 调整商品结构

给每个商品对象新增专属的折扣字段,若有定义商品interface同步更新即可:

// 商品接口示例
interface Product {
  name: string;
  price: number;
  // 新增字段:单个商品的折扣率、折扣额、折后价
  discount?: number;
  discountTotal?: number;
  finalPrice?: number;
}

// 组件内可保留全局总折后价字段,用于计算所有商品累计折后金额
totalWithDiscount: number = 0;

2. 重写折扣计算函数

直接传入当前操作的商品对象,仅修改该商品的折扣属性,再按需重新计算累计总折后价:

calculateDiscount(prod: Product) {
  const discount = prod.discount ?? 0;
  // 仅更新当前商品的折扣相关值
  prod.discountTotal = (prod.price * discount) / 100;
  prod.finalPrice = prod.price - prod.discountTotal;
  
  // 若需要计算所有商品的总折后金额,重新求和即可
  this.totalWithDiscount = this.products.reduce((sum, item) => {
    return sum + (item.finalPrice ?? item.price);
  }, 0);
}

3. 修改HTML模板

将输入框的双向绑定改为当前商品自身的discount字段,同时把商品对象传入计算函数:

<table>
    <thead>
        <tr>
            <th>product</th>
            <th>price</th>
            <th>discount</th>
            <th>discount amount</th>
            <th>final price</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let prod of products">
            <td>{{prod.name}}</td>
            <td>{{prod.price}}Dhs</td>
            <td><input type="number" (keyup.enter)="calculateDiscount(prod)" [(ngModel)]="prod.discount" placeholder="0"></td>
            <td>{{prod.discountTotal ?? 0}}Dhs</td>
            <td>{{prod.finalPrice ?? prod.price}}Dhs</td>
        </tr>
    </tbody>
</table>
<!-- 可选:展示所有商品累计折后总价 -->
<div>Total payable: {{totalWithDiscount}}Dhs</div>

注意前提

确保你的Angular模块已经导入了FormsModule,否则ngModel双向绑定会失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:57:03