我有一个用于动态创建表单的Angular 7项目。我有一个父FormGroup,其中包含各种类型的嵌套FormGroup。
我希望在所有嵌套/子表单都有效之前,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;
};