4
votes

I've been doing a lot with reactive forms now and really like the concept of it. However, I'm wondering if there's an easy way to count all formControls in a formGroup, or do I have to iterate over that?

I have a complex nested formGroup structure with 6 or 7 layers, so that would save me a bit time.

Any hint is welcome :)

2
what do you mean by 6 or 7 layers? Form Groups nested in FormGroups?Tomasz Kula
I've found no quick way. You would need to count the number of nodes in the form object.Andrew Junior Howard

2 Answers

10
votes

The property controls of FormGroup is an object. To count its keys you could easily do something like:

Object.keys(yourFormGroup.controls

If have have more than one FormGroup you should anyway iterate over them.

5
votes

You can do it recursively.

const countControls = (control: AbstractControl): number => {
  if (control instanceof FormControl) {
    return 1;
  }

  if (control instanceof FormArray) {
    return control.controls.reduce((acc, curr) => acc + countControls(curr), 1)
  }

  if (control instanceof FormGroup) {
    return Object.keys(control.controls)
      .map(key => control.controls[key])
      .reduce((acc, curr) => acc + countControls(curr), 1);
  }
}

Example usage:

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  fg: FormGroup;

  constructor(private fb: FormBuilder) {
    this.fg = this.fb.group({
      two: this.fb.group({
        three: [''],
        four: [''],
        five: [''],
      }),
      six: this.fb.group({
        seven: [''],
        eight: [''],
        nine: this.fb.group({
          ten: [''],
          eleven: this.fb.array([
            this.fb.control(''),
            this.fb.control(''),
            this.fb.control(''),
          ])
        }),
      }),
    });

    // prints 14
    console.log(countControls(this.fg));  
  }
}

Live demo