angular2 dynamic form calculate amount total

后端 未结 2 1900
小蘑菇
小蘑菇 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: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));
    });
    

提交回复
热议问题