I am working with a form that includes a formArray called FinYearArray, which in turn contains another formArray called RecipientArray. Both of these arrays have formControls for the amount, and whenever there is a change in these fields, the totals need to be calculated for each financial year and each recipient country per financial year. To calculate the total for recipients, I added a formControl in the FinYearArray called 'RecipientTotal'.
// Form structure
{
"FinYearArray": [
{
"FinYear": 2022,
"FinYearAmount": 0,
"RecipientTotal": 0,
"RecipientArray": [
{
"CtryDesc": "",
"Amount": 0,
},
{
"CtryDesc": "",
"Amount": 0,
}
],
},
{
"FinYear": 2023,
"FinYearAmount": 0,
"RecipientTotal": 0,
"RecipientArray": [
{
"CtryDesc": "",
"Amount": 0,
}
],
}
],
"ProjectCode": "",
}
In my ngOnInit(), I have the following code to monitor changes in the FinYearArray formArray and automatically update the RecipientArray formArray since it is nested inside the other formArray.
// Function to calculate totals for each financial year and recipients per financial year
this.formDetailReport.get('FinYearArray').valueChanges.subscribe(values => {
this.myFinYearTotal = 0;
const ctrl = <FormArray>this.formDetailReport.controls['FinYearArray'];
// Loop through financial years
ctrl.controls.forEach(x => {
let parsed = Number(x.get('FinYearAmount').value);
this.myFinYearTotal += parsed;
});
// Loop through recipient countries for each financial year
for (let i = 0; i < ctrl.controls.length; i++) {
this.myRecipientTotal = 0;
const recipientFormArray = <FormArray>ctrl.controls[i].get('RecipientArray');
recipientFormArray.controls.forEach(x => {
let parsed = Number(x.get('Amount').value);
this.myRecipientTotal += parsed;
});
console.log('total : ' + i + ' amount : ' + this.myRecipientTotal );
// The error occurs when trying to assign the calculated value to the formControl
this.formDetailReport.controls['cFinYearGroup']['controls'][i].controls.cRecipientTotal.setValue(this.myRecipientTotal);
// ctrl[i].controls.cRecipientTotal.setValue(this.myRecipientTotal);
}
this.ref.detectChanges();
});
However, I am encountering an error:
// Error related to assigning the calculated value to the formControl
core.js:4442 ERROR RangeError: Maximum call stack size exceeded
at EuiInputNumberComponent.ngDoCheck (eui-components-next.js:11713:1)
at callHook (core.js:3285:1)
at callHooks (core.js:3251:1)
at executeInitAndCheckHooks (core.js:3203:1)
at refreshView (core.js:7395:1)
at refreshEmbeddedViews (core.js:8481:1)
at refreshView (core.js:7404:1)
at refreshComponent (core.js:8527:1)
at refreshChildComponents (core.js:7186:1)
at refreshView (core.js:7430:1)
It seems that the error is caused by the valueChange tracking every field in the formArray. Is there a way to modify it so that it only watches changes in the FinYearAmount formControl and then in the Amount formControl in the RecipientArray?