Hey there, I'm brand new to Angular and I'm trying to set up a form array with an existing array that contains multiple objects. However, I keep encountering the following error:
Cannot find control with path: 'variable-> 0 -> id'
Here is the HTML code I have:
<form [formGroup]="myForm">
<div formArrayName="box">
<div *ngFor="let b of getForm(); let i = index">
<fieldset [formGroupName]="i">
<legend> <h3>FRUIT DETAILS {{ i + 1 }}:</h3> </legend>
<label>Fruit Name: </label>
<input [formControlName]="name" />
<label>Fruit Value: </label>
<input [formControlName]="value" />
</fieldset>
</div>
</div>
<br />
</form>
<pre>{{ myForm.value | json }}</pre>
And this is the TypeScript code accompanying it:
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
box: this.fb.array([]),
});
let fruits = {
data: [{name: 'Apple', value: 10}, {name: 'Orange', value: 5},{name: 'Banana', value: 20}]
};
for (let f of fruits.data) {
const control = <FormArray>this.myForm.get('box');
control.push(this.fb.group({name: f.name, value: f.value}));
console.log(f);
}
this.myForm.patchValue({ box: fruits.data });
//console.log(this.myForm.value);
}
getForm(): any {
return this.myForm.get('box')['controls'];
}