Future Web
Future Web

Reputation: 111

Angular FormArray of controls , how to get summary?

I have FormGroup which has products formArray in it (dynamic controls which can be added or removed) :

FormGroup {
  controls {
    products (FormArray) {
      0 : {summary.value: 5}...
      1 : {summary.value: 8}..
there can be N of these controls...
    }
  }
}

Expected summary = 5+8 = 13

I want to get all summary.value and summ them. How do I do that ?

What I've done but thats not working as expected :

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

Problem with my function is that whenever I write summary in another product , it refreshes to anothers product summary number, but I want to add it to the last summary control value. I know that happens because of this line : let numericValue = 0 + Number(price), but I can't figure out how to do it in another way.

Upvotes: 0

Views: 170

Answers (1)

user4676340
user4676340

Reputation:

Reduce the entries of your object.

const formValue = {
  summaryOne: '5',
  summaryTwo: '8',
  someRandomFieldToExclude: 'LOL'
};

const totalSummary = Object
  .entries(formValue)
  .filter(([key]) => key.toLowerCase().includes('summary'))
  .reduce((p, [, v]) => p += +v, 0);
  
console.log(totalSummary);

Upvotes: 1

Related Questions