Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactive forms: Count all formControls in a formGroup

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 :)

like image 764
dave0688 Avatar asked Dec 06 '22 12:12

dave0688


2 Answers

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.

like image 73
leota Avatar answered Mar 01 '23 02:03

leota


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

like image 42
Tomasz Kula Avatar answered Mar 01 '23 04:03

Tomasz Kula