Sometimes in the development process, we may want to get the list of form controls that have validation errors in Angular Reactive Forms. To solve this problem we can use the Error property of AbstractControl class.

Here’s an example of how to achieve this:

Let´s say, we have the following template : (app-component.html)

<form  [formGroup]="myFormGroup" (ngSubmit)="onSubmit()">
  <!-- Here we have a list of controls with formControlName -->
 ...    
 <form-field>
              <label>ProjektType</sbb-label>
               <input formControlName="type"/>
    </form-field>
   <form-field>
              <label>Manager</sbb-label>
               <input formControlName="manager"/>
    </form-field>
  ...
</form>

To retrieve the list of form controls that have validation errors, let us create this function in the component ((app-component.ts)

// Assuming myFormGroup is our FormGroup instance
Object.keys(this.myFormGroup.controls).forEach(controlName => {
  const control = this.myFormGroup.get(controlName);
  if (control?.errors) {
    console.log('Control name with error: ', controlName);
    console.log('Error details: ', control.errors);
  }
});

In the above example, we iterate through each control in the formGroup using Object.keys(this.myFormGroup.controls), and then for each control, we check if it has any errors using control.errors. If errors exist, we can log the control name and the error details.

We can use this approach to retrieve the names of form controls that have validation errors and perform any necessary actions based on the error information.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *