In my FormGroup, I have a FormArray called products which contains dynamic controls that can be added or removed:
FormGroup {
controls {
products (FormArray) {
0 : {summary.value: 5}...
1 : {summary.value: 8}..
there can be N of these controls...
}
}
}
The expected summary value is 5+8 = 13.
I need to retrieve all the summary values and calculate their sum. How can I achieve this?
This is what I've attempted so far, but it's not working as intended:
calculateAllSummary(formGroup: FormGroup) {
Object.values(formGroup.controls.products['controls']).forEach((value: FormControl) => {
let summaryControl: FormControl = value['controls'].summary;
this.summarySubscription = summaryControl.valueChanges.subscribe(val => {
if(this.checkIfValuesArentTheSame(val) == true){
let price = val;
if (price != null && typeof price == "string") {
price = price.split(',').join('');
}
let numericValue = 0 + Number(price);
this.summaryValue = this.dp.transform(numericValue, '2.2-5');
};
},
(error) => {
console.log(error)
},
);
});
}
The issue with my code is that whenever I input a new summary for another product, it overrides the previous one instead of adding to it. This is due to the line
let numericValue = 0 + Number(price)
, but I'm unsure how to approach this problem differently.