Skip to content

Instantly share code, notes, and snippets.

@afrozek
Created May 24, 2023 20:45
Show Gist options
  • Save afrozek/b04bed5fa4e99224b6a40048d424f9e2 to your computer and use it in GitHub Desktop.
Save afrozek/b04bed5fa4e99224b6a40048d424f9e2 to your computer and use it in GitHub Desktop.
Angular get all form errors
getAllErrors(form: FormGroup | FormArray): { [key: string]: any } | null {
// validation via form model
let hasError = false;
const result = Object.keys(form.controls).reduce((acc, key) => {
const control = form.get(key);
// console.log('control', control);
const errors = control instanceof FormGroup || control instanceof FormArray ? this.getAllErrors(control): control.errors;
if (errors || control.status === 'INVALID') {
acc[key] = errors;
hasError = true;
}
return acc;
}, {} as { [key: string]: any });
return hasError ? result : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment