0
votes

I am working with a reactive form that has a formArray which in turn contains several formGroups.

enter image description here

For each formGroup I am getting an array of objects (depending on what they choose in the age field) for example:

For formGroupName[0] I get:

[
  0: {aseguradora: "name1", plan: "plan1", prima: 6670}
  1: {aseguradora: "name2", plan: "plan2", prima: 3272}
]

For formGroupName1 I get:

[
  0: {aseguradora: "name1", plan: "plan1", prima: 9302}
  1: {aseguradora: "name2", plan: "plan2", prima: 4616}
]

and so...

How do I get a new Array with the total sum of the prime field? Take into account that if a formGroup is eliminated, the sum would have to be recalculated.

That is, what I want as a result is:

[
  0: {aseguradora: "name1", plan: "plan1", prima: 15972}
  1: {aseguradora: "name2", plan: "plan2", prima: 7888}
]

Tried the following, if you do the sum but when a formGroup is removed it doesn't subtract that difference:

  control.at(+i).get('edad').valueChanges.subscribe( res => {

    // Here I get the Array
    this.primasFilter = this.primasSalud.filter(fil => fil.edad === res);
    this.primasFilterEdad = this.primasFilter[0].primas;
    console.log(this.primasFilterEdad);

    // Here I do the sum
    this.saludPreferencial = (this.primasFilterEdad[0].prima);
    this.totalSumSaludP += this.saludPreferencial;
    console.log(this.totalSumSaludP);

  });
1

1 Answers

0
votes

NOT use a "counter", calculate each time looping over all the values. Some like

this.totalSumSalidP=this.array.value.map(x=>x.prima).reduce((a,b)=>(+a)+(+b),0)

Should work

NOTE: in the code, "this.array" is a getter

get array(){
   return this.myForm.get(...) as FormArray
}