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

Time:09-21

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.

CodePudding user response:

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.

  • Related