Reputation: 791
I have a FormGroup
with FormArray
control filled with FormGroup
instances
someForm = this.fb.group({
days: this.fb.array([
this.fb.group({
description: ['']
})
])
})
also, I have a getter for this array
get days(): FormArray {
return this.someForm.get('days') as FormArray;
}
when I'm trying to iterate through FormArray
and assign it to [formGroup]
directive, like shown in this article
<div *ngFor="let day of days.controls">
<ng-container [formGroup]="day">
...
I'm getting
error TS2740: Type 'AbstractControl' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 3 more.
Upvotes: 17
Views: 15887
Reputation: 41
Here, this is how I solved my issue. This approach is useful when you had to pass the formGroup to the child component also
Template:
<ng-container formArrayName="days" *ngFor="let day of days;>
<form [formGroup]="day"></form>
</ng-container>
Component:
get days(): FormGroup[] {
const formArray = this.someForm?.get('days') as FormArray;
return formArray.controls as FormGroup[];
}
here I return the controls from getter as FormGroup[]
Upvotes: 4
Reputation: 121
Another workaround would be to use casting in the component.
template:
<ng-container [formGroup]="getFormGroup(day)">
component:
getFormGroup(control: AbstractControl) { return control as FormGroup; }
So that we can still utilize the control as input value to components looped in the ngFor for formArray
<ng-container *ngFor="let day of days.controls"> <childComponent [formGroup]="day"></childComponent> </ng-container>
Upvotes: 12
Reputation: 791
I found a workaround in this article, to iterate through FormGroups
by index
like:
<div *ngFor="let day of days.controls; let i=index">
<ng-container [formGroupName]="i">
...
Upvotes: 5