Created
June 24, 2019 10:46
-
-
Save Fredx87/4b1b04255cb8a27e3c0efabb6868d7d6 to your computer and use it in GitHub Desktop.
Angular get all errors from FormGroup, flatten
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
AbstractControl, | |
FormArray, | |
FormGroup, | |
ValidationErrors | |
} from '@angular/forms'; | |
function parseControlError( | |
key: string, | |
control: AbstractControl | |
): Record<string, ValidationErrors> { | |
const res: Record<string, ValidationErrors> = {}; | |
if (control instanceof FormGroup || control instanceof FormArray) { | |
const errors = getAllFormErrors(control, key); | |
if (Object.keys(errors).length > 0) { | |
Object.assign(res, errors); | |
} | |
} else if (control.errors) { | |
res[key] = control.errors; | |
} | |
return res; | |
} | |
export function getAllFormErrors( | |
form: FormGroup | FormArray, | |
path = '' | |
): Record<string, ValidationErrors> { | |
const res: Record<string, ValidationErrors> = {}; | |
if (form instanceof FormGroup) { | |
for (const key of Object.keys(form.controls)) { | |
Object.assign( | |
res, | |
parseControlError( | |
`${path ? `${path}.${key}` : key}`, | |
form.controls[key] | |
) | |
); | |
} | |
} | |
if (form instanceof FormArray) { | |
for (let i = 0; i < form.controls.length; i++) { | |
Object.assign( | |
res, | |
parseControlError(`${path ? `${path}.${i}` : i}`, form.controls[i]) | |
); | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment