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

Angular中如何计算每行Amount值且不覆盖已有值

问题描述

我在Angular项目里实现了动态添加行功能,想通过change事件获取每行的quantity和price相乘得到amount,但现在所有行的amount都会被最新计算的值覆盖。需要实现每行的amount由该行的student_quantity和price独立计算,各行值互不干扰。

原代码

添加行部分HTML

<div class="row">
  <div class="col-md-6">
    <input
      class="form-control"
      type="text"
      id="newdescription"
      [(ngModel)]="newAttribute.description"
      name="newdescription"
      placeholder="Description"
    />
  </div>
  <div class="col-md-6">
    <input
      class="form-control"
      type="text"
      id="newstudent_quantity"
      [(ngModel)]="newAttribute.student_quantity"
      name="newstudent_quantity"
      (change)="getQuantity($event)"
      placeholder="Quantity"
    />
  </div>
  <div class="col-md-6 m-1 mt-3">
    <input
      class="form-control"
      type="text"
      id="newprice"
      [(ngModel)]="newAttribute.price"
      name="newprice"
      (change)="getPrice($event)"
      placeholder="Price"
    />
  </div>
  <div class="col-md-12 d-flex justify-content-end mt-1">
    <button
      class="btn btn-default "
      type="button"
      (click)="addFieldValue()"
    >
      <i class="nav-icon fas fa-plus icon-green"></i>
    </button>
  </div>
</div>

表格展示部分HTML

<div class="card" style="background-color: #f3f3f3">
  <div class="card-body">
    <h4>Payment Details</h4>
    <div
      *ngFor="let field of fieldArray; let i = index"
      class="col-md-12"
    >
      <div class="row">
        <div class="col-md-6">
          <label for="price"> Description </label>
          <input
            [(ngModel)]="field.description"
            class="form-control"
            id="description"
            type="text"
            name="{{ field.description }}"
            ngModel
            required
            disabled
          />
          <label for="price"> Student Quantity </label>
          <input
            [(ngModel)]="field.student_quantity"
            class="form-control"
            id="student_quantity"
            type="number"
            name="{{ field.student_quantity }}"
            value=""
            ngModel
            required
            disabled
          />
        </div>
        <div class="col-md-6">
          <label for="price"> Price </label>
          <input
            [(ngModel)]="field.price"
            id="price"
            class="form-control"
            type="number"
            name="{{ field.price }}"
            ngModel
            required
            disabled
          />
          <label for="amount"> Amount </label>
          <input
            class="form-control"
            type="number"
            name=""
            ngModel
            value="{{ amount }}"
            required
            disabled
          />
        </div>
      </div>
      <div class="row">
        <div class="col-md-12 mt-1 d-flex justify-content-end">
          <button
            class="btn btn-default align-right"
            type="button"
            (click)="deleteFieldValue(i)"
          >
            <i class="nav-icon fas fa-trash-alt icon-red"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

TS文件代码

newAttribute: any = {};
fieldArray: Array<any> = [];
quantity: any;
price: any;
amount: any;

addFieldValue() {
  this.fieldArray.push(this.newAttribute);
  this.newAttribute = {};
}

deleteFieldValue(index: number) {
  this.fieldArray.splice(index, 1);
}

getPrice(event: any) {
  this.price = event.target.value;
  console.log(this.price);
}

getQuantity(event: any) {
  this.quantity = event.target.value;
  this.amount = this.price  * this.quantity ;
  console.log("amount" + this.amount);
}

解决方案

核心问题是你用了全局的amount变量,所有行都绑定这个变量,所以会被最新值覆盖。正确做法是给每行的对象添加独立的amount属性,计算时直接更新当前行的属性。

修改后的TS代码

// 初始化时给新行对象添加amount属性
newAttribute: any = { description: '', student_quantity: 0, price: 0, amount: 0 };
fieldArray: Array<any> = [];

addFieldValue() {
  // 复制对象避免引用冲突,确保每行是独立对象
  this.fieldArray.push({ ...this.newAttribute });
  // 重置新行表单
  this.newAttribute = { description: '', student_quantity: 0, price: 0, amount: 0 };
}

deleteFieldValue(index: number) {
  this.fieldArray.splice(index, 1);
}

// 统一计算当前新行的amount
calculateAmount() {
  const quantity = Number(this.newAttribute.student_quantity);
  const price = Number(this.newAttribute.price);
  // 直接更新当前新行的amount属性
  this.newAttribute.amount = quantity * price;
}

修改后的添加行HTML

<div class="row">
  <div class="col-md-6">
    <input
      class="form-control"
      type="text"
      id="newdescription"
      [(ngModel)]="newAttribute.description"
      name="newdescription"
      placeholder="Description"
    />
  </div>
  <div class="col-md-6">
    <input
      class="form-control"
      type="number" <!-- 改为number类型,避免字符串相乘问题 -->
      id="newstudent_quantity"
      [(ngModel)]="newAttribute.student_quantity"
      name="newstudent_quantity"
      (change)="calculateAmount()" <!-- 调用统一计算方法 -->
      placeholder="Quantity"
    />
  </div>
  <div class="col-md-6 m-1 mt-3">
    <input
      class="form-control"
      type="number" <!-- 改为number类型 -->
      id="newprice"
      [(ngModel)]="newAttribute.price"
      name="newprice"
      (change)="calculateAmount()" <!-- 调用统一计算方法 -->
      placeholder="Price"
    />
  </div>
  <div class="col-md-12 d-flex justify-content-end mt-1">
    <button
      class="btn btn-default "
      type="button"
      (click)="addFieldValue()"
    >
      <i class="nav-icon fas fa-plus icon-green"></i>
    </button>
  </div>
</div>

修改后的表格展示HTML

<div class="card" style="background-color: #f3f3f3">
  <div class="card-body">
    <h4>Payment Details</h4>
    <div
      *ngFor="let field of fieldArray; let i = index"
      class="col-md-12"
    >
      <div class="row">
        <div class="col-md-6">
          <label for="description-{{i}}"> Description </label>
          <input
            [(ngModel)]="field.description"
            class="form-control"
            id="description-{{i}}" <!-- 设置唯一ID,避免表单冲突 -->
            type="text"
            name="description-{{i}}" <!-- 设置唯一name -->
            required
            disabled
          />
          <label for="student-quantity-{{i}}"> Student Quantity </label>
          <input
            [(ngModel)]="field.student_quantity"
            class="form-control"
            id="student-quantity-{{i}}"
            type="number"
            name="student-quantity-{{i}}"
            required
            disabled
          />
        </div>
        <div class="col-md-6">
          <label for="price-{{i}}"> Price </label>
          <input
            [(ngModel)]="field.price"
            id="price-{{i}}"
            class="form-control"
            type="number"
            name="price-{{i}}"
            required
            disabled
          />
          <label for="amount-{{i}}"> Amount </label>
          <input
            class="form-control"
            type="number"
            name="amount-{{i}}"
            [(ngModel)]="field.amount" <!-- 绑定当前行的amount属性 -->
            required
            disabled
          />
        </div>
      </div>
      <div class="row">
        <div class="col-md-12 mt-1 d-flex justify-content-end">
          <button
            class="btn btn-default align-right"
            type="button"
            (click)="deleteFieldValue(i)"
          >
            <i class="nav-icon fas fa-trash-alt icon-red"></i>
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:16:09