My Angular reactive form includes several FormControl elements and one FormArray element.
competitionForm!: FormGroup;
this.competitionForm = new FormGroup({
name: new FormControl(this.competition.name, []),
about: new FormControl(this.competition.about, []),
rules: new FormControl(this.competition.rules, []),
competitorNames: new FormArray([]),
});
The FormArray competitorNames
contains an array of FormControl elements with string values. I have connected the competitionForm
to a form in my HTML template using a custom input component (app-input
). This component takes a FormControl
as input: [control].
<form [formGroup]="competitionForm">
<div formArrayName="competitorNames">
<ng-container *ngFor="let competitor of refCompetitorNames.controls">
<app-input
[control]="$any(competitor)"
[placeholder]="'name'"
[type]="'text'"
></app-input>
</ng-container>
</div>
</form>
get refCompetitorNames() {
return this.competitionForm.get('competitorNames') as FormArray;
}
When I retrieve the form data using
this.competitionForm.value.competitorNames
, it always returns the same data regardless of entering new values in the input element. However, the input elements display the values correctly, indicating that the template form is bound to competitionForm
.
This method works fine for FormControl elements but faces issues with FormArray elements. Below is an example of how I pass control for a single FormControl, where updated data is obtained as expected.
The key difference lies in how I pass the control.
<form [formGroup]="competitionForm">
<app-input
[control]="$any(competitionForm.controls).name"
[placeholder]="'name'"
[type]="'text'"
></app-input>
</form>
Edit: Issue Resolved
I have identified the problem and found a solution by accessing form data differently. Using
this.refCompetitorNames.at(i).value
now retrieves the correct data. However, I am still unsure why this.competitionForm.value.competitorNames
does not reflect updated data (specifically with FormArray).