In my Angular application, I am working with a reactive form that contains a formArray of formGroups named sections:
sectionForm = new FormGroup({
title: new FormControl<string>('New Section', {nonNullable: true, validators: [Validators.required]}),
subTitle: new FormControl<string>('section sub title', {nonNullable: true}),
description: new FormControl<string>('description', {nonNullable: true}),
});
sessionForm = new FormGroup({
title: new FormControl<string>('', {nonNullable: true, validators: [Validators.required]}),
subTitle: new FormControl<string>('', {nonNullable: true, validators: [Validators.required]}),
description: new FormControl<string>('', {nonNullable: true, validators: [Validators.required]}),
sections: new FormArray([this.sectionForm])
});
I am using reactive forms and I'm trying to create the corresponding HTML form structure. The following code snippet is part of my form design where I am attempting to use the control flow to display the sections form group inside the form array:
<form [formGroup]="sessionForm" class="k-form k-form-md">
<fieldset class="k-form-fieldset">
<!-- other form controls ........ -->
<div cy-data="session-sections">
@for (section of sessionForm.controls.sections.controls; track $index) {
<div forGroupName="section">
<kendo-formfield cy-data="section-title">
<kendo-label [for]="sectiontitle" text="Section Title"></kendo-label>
<kendo-textbox
#sectiontitle
class="text-input"
formControlName="title"
[clearButton]="true"
required
></kendo-textbox>
<kendo-formerror>Error:Section Title Required</kendo-formerror>
</kendo-formfield>
<kendo-formfield cy-data="section-subtitle">
<kendo-label [for]="sectionsubtitle" text="Section Sub Title"></kendo-label>
<kendo-textbox
#sectionsubtitle
class="text-input"
formControlName="subTitle"
[clearButton]="true"
required
></kendo-textbox>
<kendo-formerror>Error:Section Sub Title Required</kendo-formerror>
</kendo-formfield>
<kendo-formfield cy-data="section-description">
<kendo-label [for]="sectiondescription" text="Section Description"></kendo-label>
<kendo-textarea
#sectiondescription
class="text-input"
formControlName="description"
required
></kendo-textarea>
<kendo-formerror>Error:Section Description Required</kendo-formerror>
</kendo-formfield>
</div>
}
</div>
</fieldset>
</form>
THE ISSUE:
The inputs mentioned above, which have the same name as the parent form group, are binding to the controls in the parent form group instead of the controls within the form array. Therefore, any input in the sectionTitle field updates the parent title property.
I tried using the formGroupName within the div to set it to section
<div forGroupName="section">
with the hope of changing the context for the controls inside it. However, this approach did not work as expected.
I need assistance in correctly binding the controls inside the form array, considering that there will be multiple "section" form groups within that array, each needing to render its respective controls.