I have got a requirement to present all errors of very complex FormGroup control which contains FormControls, FromGroups and FormArrays
i tried to fimd simple solution but I was not able to find the perfect solution which support all types of controls so i have develop the following simple recursive function and I am sharring with all:
export interface FieldError {
formGroupName: string;
fieldName: string;
errorCode: string;
}
export function getFormErrors(
control: AbstractControl,
formGroupName: string,
fieldName: string,
errors: FieldError[]) {
if (control instanceof FormGroup) {
Object.keys(control.controls).forEach(controlName => {
let formControl = control.get(controlName);
if (formControl) {
let fGroupName = formGroupName + "-" + controlName;
getFormErrors(formControl, fGroupName, controlName, errors);
}
})
}
if (control instanceof FormArray) {
control.controls.forEach((fControl: AbstractControl, index) => {
let fGroupName = formGroupName + "-" + index;
getFormErrors(fControl, fGroupName, "Array", errors);
})
}
if (control instanceof FormControl) {
const controlErrors: ValidationErrors | null = control.errors;
if (controlErrors) {
Object.keys(controlErrors).forEach(errorCode => {
errors.push({
formGroupName: formGroupName,
fieldName: fieldName,
errorCode: errorCode
})
});
}
}
}
the usage is as follow:
let errors: FieldError[] = []
getFormErrors(YOUR_FORM_GROUP, "root", "", errors);