When discussing Reactive Forms, the query arises about determining if a FormGroup contains a child control that is both invalid
and touched
, without having to inspect the entire structure of the FormGroup
.
The issue lies in how the FormGroup
becomes marked as touched
once any of its children are touched, and is labeled as invalid
as soon as any of its children are deemed invalid. However, there seems to be no straightforward method to check for a child that meets both criteria: being invalid
and touched
.
In essence, the goal is to accomplish this task without manually traversing through the FormGroup
:
function traverseFormGroup(formGroup: FormGroup): boolean {
let hasErrors = false;
for (const key of Object.keys(formGroup)) {
const child = formGroup.get(key);
hasErrors = child instanceof FormGroup || child instanceof FormArray
? hasErrors || getFormValidationErrors(child)
: hasErrors || !!child && child.errors !== null && child.touched;
if (hasErrors) {
return true;
}
}
return hasErrors;
}