I need to create as many input fields as there are records in my array.
I am getting the following error when trying to do this:
Cannot find control with path: 'data -> 1 -> value'
How to fix it?
html:
<form [formGroup]="form">
<div *ngIf="subCategoriesParams$ | async as subCategoryParams">
<ng-container *ngFor="let params of subCategoryParams.params; let i = index"
formArrayName="data">
<div formGroupName="{{i}}">
<div >
<label >
{{params.paramsName}}
</label>
<input type="text" formControlName="value"
(change)="onChangeEvent(params)">
</div>
</div>
</ng-container>
</div>
</form>
<button (click)="save()">Save</button>
ts:
public get data() {
return this.form.get('data') as FormArray;
}
initializeForm(): void {
this.form = this.fb.group({
data: this.fb.array([
this.fb.group({
params: [this.inp, Validators.required],
category: [this.selectedDescendants, Validators.required],
value: ['', Validators.required],
})
])
});
}
loadParams() {
this.subCategoriesParams$ =
this.categoryService.findOne(this.selectedDescendants);
}
CodePudding user response:
Issue & Concern
You are iterating i (formGroupName) based on subCategoryParams.params but not based on formArray.
And from the above code, I don't see any (FormGroup) value being initialized to data (FormArray).
Hence, let's say subCategoryParams.params with length: 3, while data with length of 0. That's why you faced the error mentioned.
Solution
Make sure your data (FormArray) length must be exact with the length of subCategoryParams.params by adding FormGroup instance to FormArray.
initializeForm(): void {
...
this.subCategoriesParams$.forEach((value) => {
for (let param of value.params) {
this.data.push(
this.fb.group({
params: [this.inp, Validators.required],
category: [this.selectedDescendants, Validators.required],
value: ['', Validators.required],
})
);
}
});
}
Note:
- For safer (real answer), you have to iterate over
data.controls(FormArray). - Below solution is just to fix in case you are keen to iterate over
subCategoryParams.params.
