Angular – Get errors in reactive form with loop for the FormArray

Angular – Get errors in reactive form with loop for the FormArray

When working with reactive forms in Angular, it is common to encounter scenarios where you need to display errors for each control in a FormArray. In this blog post, we will explore different solutions to achieve this.

Solution 1: Using a loop and FormGroup.get() method

One way to get errors for each control in a FormArray is by using a loop and the FormGroup.get() method. This method allows us to access the FormControl instance for each control in the FormArray.

const formArray = this.form.get('myFormArray') as FormArray;

for (let i = 0; i < formArray.length; i++) {
  const control = formArray.at(i);
  
  if (control.invalid) {
    // Display error message for this control
    console.log(control.errors);
  }
}

In the code snippet above, we first retrieve the FormArray instance using the FormGroup.get() method. Then, we iterate over each control in the FormArray using a for loop. Inside the loop, we check if the control is invalid and if so, we display the error message using console.log().

Solution 2: Using a custom directive

Another approach to get errors for each control in a FormArray is by creating a custom directive. This directive can be applied to each control in the FormArray and will handle the display of error messages.

import { Directive, Input, OnInit } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[formArrayError]'
})
export class FormArrayErrorDirective implements OnInit {
  @Input('formArrayError') controlName: string;

  constructor(private ngControl: NgControl) { }

  ngOnInit() {
    const control = this.ngControl.control;
    
    if (control.invalid) {
      // Display error message for this control
      console.log(control.errors);
    }
  }
}

In the code snippet above, we define a custom directive called FormArrayErrorDirective. This directive takes an input parameter controlName which represents the name of the control in the FormArray. Inside the ngOnInit() method, we retrieve the control instance using this.ngControl.control and check if it is invalid. If it is, we display the error message using console.log().

Conclusion

By using either a loop and the FormGroup.get() method or a custom directive, you can easily get errors for each control in a FormArray in Angular. Choose the solution that best fits your needs and implement it in your project.


Posted

in

by

Tags:

Comments

Leave a Reply

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