Angular6中的嵌套表单组

时间:2019-01-19 15:23:06

标签: angular

我正在尝试在Angular6中创建嵌套表单组。

serviceItemForm: FormGroup;
apiForm : FormGroup;

this.serviceItemForm = this.fb.group({
  'name': new FormControl('', Validators.required),
  'description': new FormControl('', Validators.required),
  'categoryIds': new FormControl([], Validators.required),
  'tags': [],
  'status': '',
  'orderFormType': new FormControl([], Validators.required),
  'orderFormKey': new FormControl([], Validators.required),
  'workflow': [],
  'orderFormAction': new FormControl('', Validators.required),
  'customUI': new FormControl(''),
  'api': this.fb.group({
    'apiurl': new FormControl(''),
    'apimethod': new FormControl(''),
    'headers': this.fb.array([]),
    'payload': '',
  }),
  'userGroup': []
});

this.apiForm = this.serviceItemForm.get('api');

在这里this.apiForm在VSCode中给出了类似Type 'AbstractControl' is not assignable to type 'FormGroup'. Property 'controls' is missing in type 'AbstractControl'.的错误。

请帮助我如何在angular-6中使用嵌套表单组

2 个答案:

答案 0 :(得分:0)

如果您检查任何嵌套(或父项)FormGroup的typeof,它将返回始终对象。所以您可以做的只是像这样对类型对象的变量进行类型转换-

apiForm : Object;
...
this.apiForm = this.serviceItemForm.get('api');

否则,您可以在像这样将变量赋值时进行类型转换-

apiForm : FormGroup;
this.apiForm = (<FormGroup>this.serviceItemForm.get['api']);

答案 1 :(得分:0)

您可以尝试以下代码:

serviceItemForm: FormGroup;
apiForm : FormGroup;

this.apiForm = this.fb.group({
    'apiurl': new FormControl(''),
    'apimethod': new FormControl(''),
    'headers': this.fb.array([]),
    'payload': '',
  });

this.serviceItemForm = this.fb.group({
  'name': new FormControl('', Validators.required),
  'description': new FormControl('', Validators.required),
  'categoryIds': new FormControl([], Validators.required),
  'tags': [],
  'status': '',
  'orderFormType': new FormControl([], Validators.required),
  'orderFormKey': new FormControl([], Validators.required),
  'workflow': [],
  'orderFormAction': new FormControl('', Validators.required),
  'customUI': new FormControl(''),
  'api': this.apiForm,
  'userGroup': []
});