Currently, I am working on an Angular 7 project that involves dynamically generating forms. The structure consists of a parent FormGroup with nested FormGroups of different types.
My goal is to have the parentForm marked as invalid until all of the nested/subforms are valid (although my ultimate aim is to have them submitted, but I'm not there yet).
this.parentForm = new FormGroup(this.subforms, { validators: allSubModulesValidValidator });
The subforms object looks like this:
interface DynamicKeyFormGroup {
[key: string]: FormGroup;
}
subforms: DynamicKeyFormGroup = {};
I am aware that my validator implementation is incorrect, and I am struggling with designing a validator for a FormGroup as opposed to a FormControl.
The concept is to iterate through all the properties of this.subForms, which represent the nested FormGroups, and check their status. If any are found to be invalid, the parentForm should also be marked as invalid.
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;
};
In response to a comment, even after removing the validator, the parent form is considered valid while the child remains invalid: https://i.stack.imgur.com/pK19C.png