所有子控件的角度形式 updateValueAndValidity [英] Angular form updateValueAndValidity of all children controls
问题描述
在我的 Angular 4 应用程序中,我有一个包含多个控件的表单.
In my Angular 4 app, I have a form with several controls.
在某些时候我需要强制更新它们的有效性,所以我这样做:
At some points I need to force the update of their validity, so I'm doing:
this.form.get('control1').updateValueAndValidity();
this.form.get('control2').updateValueAndValidity();
this.form.get('control3').updateValueAndValidity();
// and so on....
然后:
this.form.updateValueAndValidity();
这很好用.
但是我想知道是否有更好的方法来完成同样的事情,只需在父窗体上调用一个方法.
However I was wondering if there is a better way to accomplish the same thing, by just calling one method on the parent form.
根据其文档,updateValueAndValidity()
方法:
默认情况下,它还会更新其祖先的值和有效性.
By default, it will also update the value and validity of its ancestors.
但就我而言,我需要更新其后代的价值和有效性.所以我可以去掉很多行代码.
but in my case I need to update the value and validity of its descendants. So I can get rid of many lines of code.
推荐答案
我有同样的情况要更新 FormGroup |FormArray
嵌套级控件.
I had the same situation for me to update FormGroup | FormArray
at nested level controls.
看看这个(对我有用):
check this out(worked for me):
/**
* Re-calculates the value and validation status of the entire controls tree.
*/
function updateTreeValidity(group: FormGroup | FormArray): void {
Object.keys(group.controls).forEach((key: string) => {
const abstractControl = group.controls[key];
if (abstractControl instanceof FormGroup || abstractControl instanceof FormArray) {
updateTreeValidity(abstractControl);
} else {
abstractControl.updateValueAndValidity();
}
});
}
这篇关于所有子控件的角度形式 updateValueAndValidity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!