Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find index of form from FormArray that contain error in angular?

I am working with one complex form in angular and I need some help. let me explain my scenario in detail.

I have one formArray like this :

let slides = new FormArray([]);
slides.push(getNewSlide())
slides.push(getNewSlide())
slides.push(getNewSlide())
slides.push(getNewSlide())

function getNewSlide() {
  return new FormGroup({
    name: new FormControl("", [Validators.required]),
    image: new FormControl("", [Validators.required])
  })
}

Above form will look like this :

slides = [
  { name: "ram", image: "a.png" },
  { name: "shyam", image: "b.png" },
  { name: "", image: "c.png" },             <== here is error. name is required so index should be 2
  { name: "ghanshyam", image: "d.png" },
]

I want to find index of the form from FormArray that contain any error, But I don't know how to do that. One important thing is that, this form can be nested. like one FormGroup can contain another FormGroup or FormArray

anyone know about it to deep scan whole form and find index of first error place (index of form), then please answer here. I will appreciate your ideas.

Thank you.

like image 656
Mayur Kukadiya Avatar asked Nov 06 '25 11:11

Mayur Kukadiya


1 Answers

You could loop through the formArray controls and check for errors. Like this:

findFirstInvalidControlInFormArray() {
    const index = (this.slides as FormArray).controls.findIndex(
      (control) => control.invalid
    );
    console.log(index);
  }  

If the index is -1 it means, all controls are valid.

like image 79
Abdu Manas C A Avatar answered Nov 08 '25 11:11

Abdu Manas C A