Angular. Получить все ошибки FormGroup

Для целей разработки удобно получать все ошибки разом из контролов группы или массива. Встроенного метода нет, готовыми вызовами можно получить ошибки для одного контрола.

export class FormUtils {
  /**
   * Get all errors of FormGroup
   * @param control - target form control
   */
  static getControlErrors(control: AbstractControl): ValidationErrors | null {
    if (control instanceof FormControl) {
      // Return FormControl errors or null
      return control.errors ?? null;
    }
    if (control instanceof FormGroup) {
      const groupErrors = control.errors;
      // Form group can contain errors itself, in that case add'em
      const formErrors = groupErrors ? { groupErrors } : {};
      Object.keys(control.controls).forEach(key => {
        // Recursive call of the FormGroup fields
        const error = FormUtils.getControlErrors(control.get(key));
        if (error !== null) {
          // Only add error if not null
          formErrors[key] = error;
        }
      });
      // Return FormGroup errors or null
      return Object.keys(formErrors).length > 0 ? formErrors : null;
    }
    return null;
  }
} 

Похожие записи

Angular dependency injection

Определение Provider (useClass, useValue, useFactory ), Injector. Декоратор @Inject, ключ multi: true

13 ноября 2018 г. в Angular

Angular environment service

Использование сервиса для окружения вместо прямой ссылки на environment.ts

26 января 2020 г. в Angular