我有一个动态创建表单的Angular 7项目 . 我有一个父FormGroup与各种类型的嵌套FormGroups .
我希望parentForm无效,直到所有嵌套/子表单都有效(实际上希望它们已提交但尚未到达) .
this.parentForm = new FormGroup(this.subforms, { validators: allSubModulesValidValidator });
this.subforms是这样的对象:
interface DynamicKeyFormGroup {
[key: string]: FormGroup;
}
subforms: DynamicKeyFormGroup = {};
我知道我的验证器是错误的,但我无法弄清楚如何为FormGroup和FormControl设计验证器 .
我的想法是,我试图遍历所有this.subForms的属性,这些属性是嵌套的FormGroups,然后检查它们的状态 . 如果有任何无效,请将parentForm标记为无效 .
const allSubModulesValidValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
const controls = control.controls;
for (const key in controls) {
if (controls.hasOwnProperty(key)) {
if (!(controls[key].status === 'valid')) {
return { 'allSubModulesValid': true };
}
}
}
return null;
};
回应评论 . 删除验证程序后,父项在子项无效时有效: