You need to enable JavaScript to run this app. 如何在Angular中动态添加表单元素并实现单行金额动态计算
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中动态添加表单元素并实现单行金额动态计算

问题根因

你当前所有行总金额同步更新的核心原因是:所有动态生成的表单行都绑定了组件全局的同一组变量(unitprice/quantity/totalprice等),任意一行修改了变量值,所有行的绑定都会同步更新,自然就会出现所有行总金额一致的问题。


修复方案

1. 调整TS代码

把原来存数字的containers数组改造成存储每行独立表单数据的对象数组,保证每行数据隔离:

// 首先调整containers的定义,初始为空数组
containers: Array<{
  productname: string;
  quantity: number;
  unitprice: number;
  totalprice: number;
}> = [];

todoList(event) {
  // 新增行时插入独立的空数据对象
  this.containers.push({
    productname: '',
    quantity: 0,
    unitprice: 0,
    totalprice: 0
  });
}

// 计算时传入当前行下标,仅修改当前行的总金额
findsumdata(index: number) {
  const currentRow = this.containers[index];
  currentRow.totalprice = currentRow.unitprice * currentRow.quantity;
}

removefields(index: number) {
  // 按行下标删除对应行
  this.containers.splice(index, 1);
}

2. 调整HTML绑定

修改循环逻辑,绑定每行独立的对象属性,同时给每个表单控件的name属性加下标区分,避免Angular表单绑定冲突:

<input type="submit" id="submit" class="btn btn-success btn-lg active" (click)="todoList($event)"
       value="AddItem" style="text-align: center; margin: 0 inherit;" />
<div class="form-inline">
  &nbsp; &nbsp; &nbsp;
  <!-- 遍历的时候获取当前行下标index -->
  <div class="form-inline" *ngFor="let container of containers; let index = index">
    <div class="form-group">
      <div class="col-sm-12">
        <label>ProductName:</label>
        <input type="text" name="productname-{{index}}" class="form-control"
               [(ngModel)]="container.productname" maxlength="4" onkeyup="this.value=this.value.replace(/[^\d]/,'')">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-12">
        <label>Quantity:</label>
        <input type="text" name="quantity-{{index}}" class="form-control" [(ngModel)]="container.quantity"
               maxlength="4" (ngModelChange)="findsumdata(index)" onkeyup="this.value=this.value.replace(/[^\d]/,'')">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-12">
        <label>UnitPrice:</label>
        <input type="text" name="unitprice-{{index}}" class="form-control"
               [(ngModel)]="container.unitprice" maxlength="4" (ngModelChange)="findsumdata(index)"
               onkeyup="this.value=this.value.replace(/[^\d]/,'')">
      </div>
    </div>
    <div class="form-group">
      <div class="col-sm-12">
        <label>TotalAmount:</label>
        <input type="text" name="totalamount-{{index}}"
               class="form-control" [(ngModel)]="container.totalprice" maxlength="4"
               onkeyup="this.value=this.value.replace(/[^\d]/,'')" disabled>
      </div>
    </div>
    <!-- 可选:新增删除行按钮 -->
    <button type="button" class="btn btn-danger" (click)="removefields(index)">删除行</button>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 09:09:03