angular2 dynamic form calculate amount total

后端 未结 2 1880
小蘑菇
小蘑菇 2021-01-16 12:52

Trying to calculate a total payOffs.amount (payOffs is a FormArray). Not sure how to do it properly so the total would observe changes to current and new for amounts. Here i

相关标签:
2条回答
  • 2021-01-16 13:39

    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

    0 讨论(0)
  • 2021-01-16 13:41

    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));
    });
    
    0 讨论(0)
提交回复
热议问题