raju
raju

Reputation: 6936

Nested form group in Angular6

I am trying to created nested form group in 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');

Here this.apiForm is giving error like Type 'AbstractControl' is not assignable to type 'FormGroup'. Property 'controls' is missing in type 'AbstractControl'. In VSCode.

Please help how can I use nested form-group in angular-6

Upvotes: 1

Views: 103

Answers (2)

Vikash Dahiya
Vikash Dahiya

Reputation: 5801

You can try below code:

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': []
});

Upvotes: 1

Pardeep Jain
Pardeep Jain

Reputation: 86740

If you check typeof of any nested (or parent) FormGroup it will return always object. so what you can do is just typecast your variable of type object like this -

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

Else, You can typecast at the time of assigning value to a variable like this -

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

Upvotes: 0

Related Questions