'Type AbstractControl is not assignable to type FormGroup
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.
Solution 1:[1]
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">
...
Solution 2:[2]
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>
Solution 3:[3]
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[]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Antony |
Solution 2 | otewguy otewguy |
Solution 3 |