Angular form builder vs form control and form group
I have gone through the Angular Official Docs and on the Reactive Forms Part I have seen that:
The FormBuilder service is an injectable provider that is provided with the reactive forms module.
If you read more you see that the form builder is a service that does the same things as form-group, form-control and form-array. The official docs describe it as:
Creating form control instances manually can become repetitive when dealing with multiple forms. The FormBuilder service provides convenient methods for generating controls.
So basically saying that FormBuilder is a service that is trying to help us reduce boiler-plate code. An example of how FormBuilder is used to reduce boilerplate code can be seen here. To answer the question:
So is there any advantage of one over the other way of doing it or is it just preference?
Well, there is no technical advantage and whichever code you use all boils down to your preference.
This example is here
To note: you can combine the FormControl(s) to either format.
emailFormControl = new FormControl(undefined, [
Validators.required,
Validators.email,
]);
With FormGroup:
export class ProfileEditorComponent {
profileForm = new FormGroup({
email: this.emailFormControl,
firstName: new FormControl(''),
lastName: new FormControl(''),
address: new FormGroup({
street: new FormControl(''),
city: new FormControl(''),
state: new FormControl(''),
zip: new FormControl('')
})
});
}
With FormBuilder:
export class ProfileEditorComponent {
constructor(private fb: FormBuilder) { }
profileForm = this.fb.group({
email: this.emailFormControl,
firstName: [''],
lastName: [''],
address: this.fb.group({
street: [''],
city: [''],
state: [''],
zip: ['']
}),
});
}