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 :)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With