I have the following form
in Angular created with FormBuilder
:
constructor(private fb: FormBuilder) {
this.myForm = fb.group({
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.