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;
  }
} 

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

Как добавить ng-bootstrap компоненты в проект Angular-CLI?

Покажу на примере нового проекта.

ng new project_name
cd project_name
npm install --save bootstrap@next
npm install --save @ng-bootstrap/ng-bootstrap

В angular-cli.json в секцию style надо добавить наш CSS, чтобы глобально подключить стили.

  "styles": [
    "styles.css",
    "../node_modules/bootstrap/dist/css/bootstrap.min.css"
  ],
17 августа 2017 г. в Angular