问题描述
我试图获取一些可以使用FormBuilder样式与FormGroup样式组件一起工作的代码。我需要添加一个包含集合的子组件。因此,工作版本具有:
createFormGroup(order: Order): FormGroup {
const group = this.fb.group({
id: [order.id],invoiceNumber: [order.invoiceNumber,Validators.required],customerName: [order.customerName,total: [order.total],orderItems: this.fb.array([])
});
order.orderItems.forEach(x => {
var formArray = group.controls.orderItems as FormArray;
formArray.push(this.createOrderItem(x));
});
return group;
}
我的版本有
this.orderForm = new FormGroup({
'reqDetails': new FormGroup({
'reqDesc': new FormControl(this.order.reqDesc,Validators.required),'orderNumber': new FormControl(this.order.orderNumber),'selectedvendorId': new FormControl(this.order.ordervendorId)
}),'itemsDetails': new FormGroup({
'isItPurchase': new FormControl(this.order.isItPurchase),'orderItems' : new FormArray(this.orderItems)
})
});
为什么会出现错误
"message": "Argument of type 'OrderItem[]' is not assignable to parameter of type 'AbstractControl[]'.\n Type 'OrderItem' is missing the following properties from type 'AbstractControl': validator,asyncValidator,_parent,_asyncValidationSubscription,and 44 more.",
解决方法
this.orderItems
应该返回FormControl的数组。
像您的工作示例一样
order.orderItems.forEach(x => {
var formArray = group.controls.orderItems as FormArray;
formArray.push(this.createOrderItem(x)); // <-- here is returning array of FormControl
});