Angular Form Builder Vs Form Control And Form Group


Answer :

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

With FormControl:

constructor(private fb: FormBuilder) { } profileForm = new FormGroup({   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 {   profileForm = this.fb.group({     firstName: [''],     lastName: [''],     address: this.fb.group({       street: [''],       city: [''],       state: [''],       zip: ['']     }),   }); 

Its almost the same. I always try to use form builder because its more flexible specially when we are talking about dynamic form creation. If you have dynamic form creation you just path it an object and it will return you FormGroup.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?