I am currently dealing with a reactive form that consists of a formArray containing multiple formGroups.
https://i.sstatic.net/LSaZG.png
Each formGroup corresponds to an array of objects based on the selection made in the age field. For example:
For formGroupName[0], the resulting array is:
[
0: {aseguradora: "name1", plan: "plan1", prima: 6670}
1: {aseguradora: "name2", plan: "plan2", prima: 3272}
]
For formGroupName1, the array looks like this:
[
0: {aseguradora: "name1", plan: "plan1", prima: 9302}
1: {aseguradora: "name2", plan: "plan2", prima: 4616}
]
This pattern continues for other formGroups as well.
Now, my goal is to create a new Array that sums up the prima
values from all groups. If a formGroup is removed, the sum should be adjusted accordingly.
In essence, I want the final result to be:
[
0: {aseguradora: "name1", plan: "plan1", prima: 15972}
1: {aseguradora: "name2", plan: "plan2", prima: 7888}
]
I have attempted the following approach, which calculates the sum but doesn't adjust it when a formGroup is deleted:
control.at(+i).get('edad').valueChanges.subscribe( res => {
// Fetching the Array
this.primasFilter = this.primasSalud.filter(fil => fil.edad === res);
this.primasFilterEdad = this.primasFilter[0].primas;
console.log(this.primasFilterEdad);
// Calculating the sum
this.saludPreferencial = (this.primasFilterEdad[0].prima);
this.totalSumSaludP += this.saludPreferencial;
console.log(this.totalSumSaludP);
});