angular2 dynamic form calculate amount total

旧时模样 提交于 2019-12-01 11:56:29
Daniel Mylian

Or you could observe changes on the whole form array, by subscribing to the changes in the constructor.

this.form.controls.payOffs.valueChanges.subscribe((change) => {
  const calculateAmount = (payoffs: any[]): number => {
    return payoffs.reduce((acc, current) => {
       // also handling case when a new pay off is added with amount of null
       return acc + parseFloat(current.amount || 0);
    }, 0);
  }

  console.log(calculateAmount(this.form.controls.payOffs.value));
});

I added a function:

// calculate a sum of all payoffs
sumPayOffs() {
  return this.myModel.payOffs.reduce((sum, val) => sum + val.amount, 0);
}

and in HTML (just before "Add Pay Off" button) I added readonly number field, displaying the sum:

<td>
  <input type="number" step="0.01" class="sum" readonly size=6 [value]="sumPayOffs()">
</td>
<td colspan="3" style="text-align: center; padding: .5em;">
  <button (click)="addPayOff($event)" 
          style="color: white; background: rgba(0, 150, 0, 1)">Add Pay Off</button>
</td>

I changed pay offs field type from text to number, so inserted into mode value will be numeric.

Updated plunker: http://plnkr.co/edit/Q5HYcpnPQosSYvk2KkoP?p=preview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!