0

在此处输入图像描述

我想添加 apple,orange 和 mango 的值,然后想得到总的值。下面是我尝试过的代码。

  <div class="row col-12 " ngModelGroup="cntMap">
    <div class="form-group col-6">
        <label for="total">Total</label>
        <div class="clearfix">
          <input type="text" value="{{totalCount}}" class="form-control"
             name="totalCnt" [maxlength]="30" placeholder="Total" #totalCnt="ngModel" ngModel 
             [(ngModel)]="form.totalCnt">
        </div>
     </div>
     <div class="form-group col-6 ml-auto">
      <label for="APPLE">Apple</label>
      <div class="clearfix">
        <input type="text" class="form-control" name="APPLE" [maxlength]="30" placeholder="Enter" 
          #APPLE="ngModel" ngModel [(ngModel)]="form.APPLE" (change)="getCount($event)">
      </div>
     </div>
     <div class="form-group col-6 ml-auto">
      <label for="ORANGE">Orange</label>
      <div class="clearfix">
        <input type="text" class="form-control" name="ORANGE" [maxlength]="30" placeholder="Enter" 
          #ORANGE="ngModel" ngModel [(ngModel)]="form.ORANGE" (change)="getCount($event)">
      </div>
     </div>
     <div class="form-group col-6 ml-auto">
      <label for="MANGO">Mango</label>
      <div class="clearfix">
        <input type="text" class="form-control" name="MANGO" [maxlength]="30" placeholder="Enter" 
          #MANGO="ngModel" ngModel [(ngModel)]="form.MANGO" (change)="getCount($event)">
      </div>
     </div>
  </div>  

在 component.ts 文件中

  getCount(event: any) {
    var c = event.target.value;
    this.totalCount += parseInt(c);
    console.log("totalCount ", this.totalCount );
  }

问题:

当我在输入中添加值时,它会添加如下计数:10+10+10=30

之后,当我将 Apple 值从 10 更改为 8 时,总值就像:10+10+10+8=38 这意味着不清除输入框中的数据,它正在添加值 8。

谁能帮我解决这个问题。

4

1 回答 1

0

当前发生的流程是正确的,因为getCount()正在将新值添加到现有总数中。

相反,您应该做的是在每个更改事件上,重新添加所有三个输入字段中的值。

getCount(event: any) {
  this.totalCount = parseInt(this.form.APPLE) + parseInt(this.form.ORANGE) + parseInt(this.form.MANGO);
  console.log("totalCount ", this.totalCount );
}
于 2020-05-02T07:54:02.017 回答