首页 > 解决方案 > 来自 FormBuilder 的角度转换。样式到 FormGroup。如何创建Formarray?

问题描述

我正在尝试获取一些有效的代码,并使用 FormBuilder 样式与我的 FormGroup 样式组件一起使用。我需要添加一个包含集合的子组件。所以工作版本有:

 createFormGroup(order: Order): FormGroup {
    const  group = this.fb.group({
        id: [order.id],
        invoiceNumber: [order.invoiceNumber, Validators.required],
        customerName: [order.customerName, Validators.required],
        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.",

标签: angularformgroupsangular2-formbuilder

解决方案


FormControl应该this.orderItems返回和数组。

就像你的工作示例

order.orderItems.forEach(x => {
  var formArray = group.controls.orderItems as FormArray;
  formArray.push(this.createOrderItem(x)); // <-- here is returning array of FormControl
});

推荐阅读