get all form errors angular 1

get all form errors angular

getAllErrors(form: FormGroup | FormArray): { [key: string]: any; } | null {
    let hasError = false;
    const result = Object.keys(form.controls).reduce((acc, key) => {
        const control = form.get(key);
        const errors = (control instanceof FormGroup || control instanceof FormArray)
            ? this.getAllErrors(control)
            : control.errors;
        if (errors) {
            acc[key] = errors;
            hasError = true;
        }
        return acc;
    }, {} as { [key: string]: any; });
    return hasError ? result : null;
}

Here is what the above code is Doing:
1. It’s iterating over all the controls in the form.
2. If the control is a FormGroup or FormArray, it’s recursively calling the same function to get the errors for that control.
3. If the control is a FormControl, it’s getting the errors for that control.
4. It’s returning the errors for the form.

Now, we can use this function to get the errors for the form.

Similar Posts