【发布时间】:2019-02-05 14:33:53
【问题描述】:
我需要使用 FormArray 从角度 6 创建更新。
我在editfrom.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>
但是当页面加载时它会显示这个错误:
ERROR TypeError: value.forEach 不是函数 在 FormArray.push../node_modules/@angular/forms/fesm5/forms.js.FormArray.setValue (forms.js:3545)
有什么问题?
【问题讨论】:
-
this.editFG.get('values')的返回需要检查,因为它不是数组。您应该防御性地测试该返回,因为它来自不受控制的来源。如果无效,则抛出并处理或返回一个空数组。 -
this.valueIngrident是什么? -
@User5842
valueIngrident=new FormArray([]) -
@RandyCasburn
values是数组 -
@Mr-Programer - 阅读下面的答案!
标签: javascript angular typescript angular6