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
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
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));
});