1

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. [email protected])
                </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.

3 Answers 3

7

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;
}
Sign up to request clarification or add additional context in comments.

Comments

2

There is a way better solution for this.

Object.keys(formGroup.errors).length

This will return us collective count of errors within a formGroup

Comments

0

This is what worked for me, based on Vikrant answer, and applied in Angular 16.

Object.keys(formGroup.controls).filter((x: string) => !!formGroup.get(x)?.errors ).length

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.