BBaysinger
BBaysinger

Reputation: 6877

Iterate Angular 2+ FormArray

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?

Upvotes: 43

Views: 83011

Answers (4)

Petro Darii
Petro Darii

Reputation: 701

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;
 });

Upvotes: 1

O-9
O-9

Reputation: 1779

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"

Upvotes: 6

Ousama
Ousama

Reputation: 2810

I solved this problem by looping through formArray.controls :

  formArray.controls.forEach((element, index) => {
    ...
  });

Upvotes: 30

Aleš Doganoc
Aleš Doganoc

Reputation: 12092

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
   }
}

Upvotes: 69

Related Questions