valueformArray内部formArray中的更改



我有一个包含一个formArray(FinYearArray(的表单,而这个表单又包含另一个formArray(RecipientArray(FinYearArray和RecipientArray都包含金额的formControl,每次这些字段发生变化时,都应按财政年度和受援国的财政年度计算总额。对于收件人的总数,我在FinYearArray中创建了一个名为"RecipientTotal"的formControl

//structure of the form
{
"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": "",
}

在我的ngOnInit((中我有这个代码来检查FinYearArray窗体Array和RecipientArray窗体Array中何时发生更改,因为它在另一个窗体Array 中

//function that calculates the totals for fin year and recipients/fin year
this.formDetailReport.get('FinYearArray').valueChanges.subscribe(values => {
this.myFinYearTotal = 0;
const ctrl = <FormArray>this.formDetailReport.controls['FinYearArray'];
//loop trough fin 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 );
// when using this code i get the error at the end of this mail
this.formDetailReport.controls['cFinYearGroup']['controls'][i].controls.cRecipientTotal.setValue(this.myRecipientTotal);
// ctrl[i].controls.cRecipientTotal.setValue(this.myRecipientTotal);
}
this.ref.detectChanges();
});

但是我收到这个错误

// error when i try to assign the calculate 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)

我想这是因为每次我更新收件人总数(cRecipientTotal formControl(时,这段代码都会被重新执行,因为formArray 中有一个valueChange

难道没有办法让这个valueChange只监视formArray内部的FinYearAmount formControl,而不是监视这个formArray的所有字段吗?以及在RecipientArray 中观察表单控制量的后记

当更新连接了valueChanges侦听器的AbstractControl时,并且您不想重新触发它(导致您正遭受的无限循环(,您可以向setValue/patchValue调用添加一个配置对象:

myFormControl.setValue(value, { emitEvent: false });

最新更新