Angular form builder vs form control and form group
Asked Answered
P

5

60

Is there any advantage of using form control and form group over form builder?

I have seen here that:

The FormBuilder provides syntactic sugar that shortens creating instances of a FormControl, FormGroup, or FormArray. It reduces the amount of boilerplate needed to build complex forms.

And I was wondering if there is any advantage of not using form-builder. I am asking this because I was going through some angular code and I saw form control and form group being used and I wondered why one would do that if there is a shorter way to do the same?

So is there any advantage of one over the other way of doing it or is it just preference?

Possible answered 7/5, 2019 at 4:47 Comment(2)
Its almost the same, only form builder will have less symbols in terms of code :)Mainz
well, take account that using form control alow us indicate {updateOn:'blur'}, Before Angular 7 you only can use formBuilder. For me it's more "natural" the use of form control, and don't need inject formBuilder, but, as you say it is just preferenceSquatter
P
77

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.

Possible answered 8/5, 2019 at 9:22 Comment(2)
One disadvantage is when you don;t really have dynamic form fields and you use formControlName="myField" or formGroup.controls.myFeild inside a template is not going to allow IDEs to detect any issues up front vs having the form controls on the component and using [formControl]="myFieldCtrl" .Murray
I have a basic question about injectable provider. Usually it typically only needs to declare the interfaces of the services it uses, rather than their concrete implementation. But FormBuilder is not an interface, it is a class.Aleece
O
41

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: ['']
    }),
  });
}
Oppose answered 13/2, 2020 at 16:18 Comment(0)
M
8

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.

Mainz answered 7/5, 2019 at 4:53 Comment(2)
What do you mean by "smaller"?Kutzenco
@Kutzenco Was long time ago, but I think I mean that syntax of form builder is smaller for instance this.fb.group({firstName: ['']}); vs new FormGroup({ firstName: new FormControl('')), but now I am not sure :) So will edit my response :)Mainz
C
3

https://github.com/angular/angular/blob/master/packages/forms/src/form_builder.ts#L81

 group(
  controlsConfig: {[key: string]: any},
  options: AbstractControlOptions|{[key: string]: any}|null = null): FormGroup {
const controls = this._reduceControls(controlsConfig);

let validators: ValidatorFn|ValidatorFn[]|null = null;
let asyncValidators: AsyncValidatorFn|AsyncValidatorFn[]|null = null;
let updateOn: FormHooks|undefined = undefined;

if (options != null) {
  if (isAbstractControlOptions(options)) {
    // `options` are `AbstractControlOptions`
    validators = options.validators != null ? options.validators : null;
    asyncValidators = options.asyncValidators != null ? options.asyncValidators : null;
    updateOn = options.updateOn != null ? options.updateOn : undefined;
  } else {
    // `options` are legacy form group options
    validators = options['validator'] != null ? options['validator'] : null;
    asyncValidators = options['asyncValidator'] != null ? options['asyncValidator'] : null;
  }
}

return new FormGroup(controls, {asyncValidators, updateOn, validators});

Method group from form builder will return same FormGroup. So your choise will do nothing with performense. Not what @rohit.khurmi095 says in his answer

Colossus answered 15/7, 2021 at 7:26 Comment(0)
C
2

Using FormBuilder over FormGroup helps to improve application performance.

FormGroup new = new object created - has to be deleted manually (NOT GOOD FOR APPLICATION MEMORY PERFORMANCE)

 this.form1 = new FormGroup({})

FormBuilder(helper class)

  • creating FormBuilder object (Removing 'new' keyword)
  • it needs to be injected in constructor

constructor(private _fb:FormBuilder) { }

 this.form1 = this._fb.group({})
    
Counterclockwise answered 7/2, 2021 at 3:18 Comment(3)
@rohit.kumar : Is there the statement in angular docs regarding your arguments ?Olaolaf
But this._fb.group() returns new FormGroup() anyway, so I don't see how there is any difference between your two code examples in terms of performance, except that the form builder version runs additional code before it creates the new form group. Can you provide more information to explain your claim in more detail?Overmatter
agreeing to what @Overmatter says. Using FormBuilder requires an instance of it, the other Form* instances need to be created anyway.Lord

© 2022 - 2024 — McMap. All rights reserved.