I am working on creating an update form in Angular 6 using FormArray.
Below is the code snippet I have in editfrom.TS
:
// Initialising FormArray
valueIngrident = new FormArray([]);
constructor(private brandService: BrandService, private PValueInfoService: ProductinfovalueService, private productinfoService: ProductinfoService, private catService: CategoryService, private produSrvice: ProductService, private route: ActivatedRoute, private fb: FormBuilder) {
this.id = +this.route.snapshot.paramMap.get('id');
this.productVM = this.produSrvice.InitialProduct();
}
ngOnInit() {
this.InitialForm();
this.GetMainCat();
}
InitialForm() {
this.editFG = this.fb.group({
productTitle: ['', Validators.compose([Validators.required])],
productName: ['', Validators.compose([Validators.required])],
color: ['', Validators.compose([Validators.required])],
productImageName: ['', Validators.compose([Validators.required])],
price: ['', Validators.compose([Validators.required])],
gurantyMonth: ['', Validators.compose([Validators.required])],
gurantyCompanyName: ['', Validators.compose([Validators.required])],
catId: ['', Validators.compose([Validators.required])],
brandId: ['', Validators.compose([Validators.required])],
values: this.valueIngrident
});
this.GetProductByID(this.id);
}
public GetProductByID(id: number) {
this.produSrvice.GetProductDetailById(id).subscribe((data) => {
this.productVM = data;
this.SelectBrand = data.brandId;
this.SelectCat = data.catId;
this.PName = this.productVM.productName;
this.editFG.setValue({
productTitle: [data.productTitle],
productName: [data.productName],
color: [data.color],
productImageName: [data.productImageName],
price: [data.price],
gurantyMonth: [data.gurantyMonth],
gurantyCompanyName: [data.gurantyCompanyName],
catId: [data.catId],
brandId: [data.brandId],
values: this.valueIngrident
});
this.ChangeFormByType(data.catId);
})
}
get ValueFormControl() {
return this.editFG.get('values') as FormArray;
}
public CreateValueFiled(PD: Productinfovalue[]) {
for (let element of PD) {
this.valueIngrident.push(
new FormGroup({
infoId: new FormControl(element.infoId),
value: new FormControl(element.value)
})
)
}
}
public ChangeFormByType(id: number) {
this.ChangeBrand(id);
this.PValueInfoService.GetAllInfoValueForUpdate(id).subscribe(
res => {
this.PD = res,
this.CreateValueFiled(this.PD)
}
)
}
And I use that in HTML :
<div class="form-inline lbin" formArrayName="values">
<div class="form-inline lbin" *ngFor="let valueCtrl of ValueFormControl.controls; let i=index" [formGroupName]="i">
<div class="form-inline lbin">
<label></label>
<input formControlName="value" >
</div>
</div>
</div>
However, when the page loads, it shows me this Error :
ERROR TypeError: value.forEach is not a function at FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray.setValue (forms.js:3545)
What could be causing this issue?