Iterate Angular 2+ FormArray
Asked Answered
M

4

43

I have a FormArray and need to iterate through each of its members.

I see there is a get method in the docs, but I don't see where to get the keys, or even the length.

How do I iterate a FormArray?

Miscellaneous answered 20/3, 2018 at 22:32 Comment(0)
C
66

You have a property controls in FormArray which is an array of AbstractControl objects. Check the specific documentation for FormArray and you will see they also inherit from AbstractControl like the FormControl you posted.

Be aware that in the controls array you can have again inside FormArray or FormGroup objects besides FormControl objects because there can be nested groups or arrays.

Here is simple example:

for (let control of formArray.controls) {
   if (control instanceof FormControl) {
      // is a FormControl
   }
   if (control instanceof FormGroup) {
      // is a FormGroup  
   }
   if (control instanceof FormArray) {
      // is a FormArray
   }
}
Continuity answered 20/3, 2018 at 23:8 Comment(4)
I actually figured it out moments ago. Thanks for the additional info.Miscellaneous
Dunno why that's not documented.Miscellaneous
This SO answer helped me: this.form = this.fb.group({ userIds: this.fb.array([]) }); const userIds = this.form.controls.userIds as FormArray; userIds.value.forEach(key => { this.clinet.updateContactGroup(key, this.groupId).subscribe();} );Ukrainian
You can iterate through formArray.controls, please see the answer belowEpistyle
E
30

I solved this problem by looping through formArray.controls :

  formArray.controls.forEach((element, index) => {
    ...
  });
Epistyle answered 13/11, 2020 at 10:23 Comment(0)
C
6

If someone needs helps with iterating them in template (like I did), you can do this.

In this case we have FormArray where each child is FormControl

get myRows(): FormControl[] {
    return (this.<your form group>.get('<field name>') as FormArray).controls as FormControl[];
  }

And in template

*ngFor="let row of myRows"
Conjoint answered 22/12, 2021 at 9:5 Comment(3)
oh btw. Now (Angular 14+) we have Typed forms so this anser is a little bit outdated. You should definetely start using them!Conjoint
can you show an exampleBladder
thanks @O-9, I was looking for same thingTonry
A
1

So, I had same situation, in my case:

adjustmentAmountArray: FormArray;

And I need sum of contingencyUsed of every FormArray item.

 adjustmentAmountArray.controls.reduce((acc, curr) => {
    return acc + curr.value.contingencyUsed;
 });
Acedia answered 21/6, 2023 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.