angulartemplateserror-handlingangular-forms

Check Error Count Angular Reactive Forms


I want to conditionally apply a css class if the error count in a form is greater than 1. How do I do this in angular4?

Component:

import { Component } from "@angular/core";
import { FormGroup, ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';

@Component({
    ...
})

export class RegisterComponent {
  complexForm : FormGroup;

  constructor(fb: FormBuilder){
    this.complexForm = fb.group({
      'emailAddress' : [null, Validators.email],
      'firstName': [null, Validators.compose([Validators.required, Validators.minLength(2)])],
      ...
    })
  }

  submitForm(value: any){
    console.log(value);
  }
}

Template:

<form [formGroup]="complexForm" (ngSubmit)="submitForm(complexForm.value)">
      <section class="form-block">
          <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['emailAddress'].valid && complexForm.controls['emailAddress'].touched}">
                <label for="formFields_1">Email Address</label>
                <input [formControl]="complexForm.controls['emailAddress']" type="text" spellcheck="false" id="formFields_1" placeholder="" size="35">
                <span *ngIf="complexForm.controls['emailAddress'].hasError('email') && complexForm.controls['emailAddress'].touched" class="tooltip-content">
                    Please enter a valid email address (ex. joan@vmware.com)
                </span>
          </div>   
          <div class="form-group" [ngClass]="{'has-error':!complexForm.controls['firstName'].valid && complexForm.controls['firstName'].touched}">
              <label for="formFields_2">First Name</label>
                <input [formControl]="complexForm.controls['firstName']" type="text" spellcheck="false" id="formFields_2" placeholder="" size="35">
                <span *ngIf="complexForm.controls['firstName'].hasError('required') && complexForm.controls['firstName'].touched" class="tooltip-content">
                    Your first name must contain at least one letter
                </span>
          </div>
     </section>
</form>

If I want to apply the class form-error to <form> if the forms error count is greater than 1, how do I do this? Thanks for your ideas.


Solution

  • I don't know of a way that Angular gives you this. You'd have to write your own method within your component class to calculate this. You'd need to add up the count of the Errors in each control.

    Something like this:

    getErrorCount(container: FormGroup): number {
        let errorCount = 0;
        for (let controlKey in container.controls) {
            if (container.controls.hasOwnProperty(controlKey)) {
                if (container.controls[controlKey].errors) {
                    errorCount += Object.keys(container.controls[controlKey].errors).length;
                    console.log(errorCount);
                }
            }
        }
        return errorCount;
    }