Setting up the form control:
formMain = this.fb.group({
details: this.fb.array([
new FormGroup({
label: new FormControl(''),
description: new FormControl(''),
})
])
});
The HTML includes dynamic input fields:
<div formArrayName="details">
<div *ngFor="let detail of formMain.value.details; index as i">
<mat-form-field appearance="fill">
<mat-label>Label of a detail</mat-label>
<input id="detail-label" matInput type="text" [value]="detail.label">
</mat-form-field>
<mat-form-field appearance="fill">
<mat-label>Description of a detail</mat-label>
<input id="detail-description" matInput type="text" [value]="detail.description">
</mat-form-field>
</div>
</div>
Initially works correctly, but when attempting to edit values in the input fields, they are not stored in the form control. This could be due to missing formControlName
.
To rectify, formControlName
and [formGroupName]="i"
were added:
<div *ngFor="let detail of formMain.value.details; index as i" [formGroupName]="i">
<mat-form-field appearance="fill">
<mat-label>Label of a detail</mat-label>
<input id="detail-label" matInput type="text" [value]="detail.label" formControlName="label">
</mat-form-field>
...
After making these changes, the input fields become uneditable. Upon inspection of the DOM, it seems that [formGroupName]="i"
is causing the issue.
<div class="mat-form-field-infix ng-tns-c97-1030"><input _ngcontent-lqv-c198="" id="detail-label" matinput="" type="text" formcontrolname="label" class="mat-input-element mat-form-field-autofill-control ng-tns-c97-1030 ng-untouched ng-pristine ng-valid cdk-text-field-autofill-monitored" ng-reflect-name="label" ng-reflect-id="detail-label" ng-reflect-type="text" ng-reflect-value="Brooklyn" aria-invalid="false" aria-required="false"><span class="mat-form-field-label-wrapper ng-tns-c97-1030"><label class="mat-form-field-label ng-tns-c97-1030 ng-star-inserted" ng-reflect-disabled="true" id="mat-form-field-label-2045" ng-reflect-ng-switch="true" for="detail-label" aria-owns="detail-label"><!--bindings={
"ng-reflect-ng-switch-case": "false"
}--><mat-label _ngcontent-lqv-c198="" class="ng-tns-c97-1030 ng-star-inserted">Label of a detail</mat-label><!--bindings={
"ng-reflect-ng-switch-case": "true"
}--><!--bindings={
"ng-reflect-ng-if": "false"
}--></label><!--bindings={
"ng-reflect-ng-if": "true"
}--></span></div>
When removing [formGroupName]="i"
, the input field values can be edited but an error is encountered:
ERROR Error: Cannot find control with path: 'details -> label'
A solution to this issue is sought.