我将为您翻译关于IT技术的内容。需要创建一个使用FormArray的Angular 6更新表单。
我在editform.TS
中使用以下代码:
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)
}
)
}
我在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>
但是当页面加载时,它显示了这个错误:
错误类型:TypeError: value.forEach 不是一个函数 位于 FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray.setValue (forms.js:3545)
问题出在哪里?
this.editFG.get('values')
的返回值,因为它不是一个数组。你应该进行防御性测试,因为它来自一个不受控制的源。如果无效,则抛出并处理或返回一个空数组。 - Randy Casburnthis.valueIngrident
是什么? - User 5842valueIngrident=new FormArray([])
@User5842valueIngrident=new FormArray([])
- Mr-Programervalues
是一个表单数组。 - Mr-Programer