How to append new FormGroup or FormControl to form
You can use addControl
method of FormGroup class as per documentation
So you can do as below :
this.myForm.addControl('newcontrol',[]);
To add upon what @ranakrunal9 said.
If you would like to use validators with addControl do the following:
this.myForm.addControl('newControl', new FormControl('', Validators.required));
Just don't forget to add the following import
import {FormControl} from "@angular/forms";
Reference to addControl: https://angular.io/api/forms/FormGroup#addControl
Reference to FormControl: https://angular.io/api/forms/FormControl
In my opinion, you could just use an intermediate variable for this purpose. Take a look at the next example:
constructor(private fb: FormBuilder) { let group = { 'name': ['', [Validators.required]], 'surname': ['', [Validators.required]], 'email': ['', [Validators.required]] }; let middlename = true; if(middlename) { group['middlename'] = ['', [Validators.required]]; } this.myForm = fb.group(group); }
Also, it would a better idea to transfer a form initiation in ngOnInit hook, instead of component constructor.