Home > Back-end >  Angular form group vs form control and form builder in Reactive Forms
Angular form group vs form control and form builder in Reactive Forms

Time:10-19

I'm new to Angular. I came across the code with three variants. I want to know what difference does these three makes implementing in the Reactive forms(Form group, Form builder, and Form control).

Is there any priority based on the application performance of one over the other way of doing it or is it just preference?

addressFormControl = new FormControl(undefined, [
        Validators.required,
        Validators.address,
      ]);



   export class BusinessComponent {
      BusinessForm = 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('')
        })
      });
    }

export class BusinessComponent {
  constructor(private fb: FormBuilder) { }    
  businessForm = this.fb.group({
    business: this.businessFormControl,
    firstName: [''],
    lastName: [''],
    address: this.fb.group({
      street: [''],
      city: [''],
      state: [''],
      zip: ['']
    }),
  });
}

CodePudding user response:

Well, there is no technical advantage and whichever code you use all boils down to your preference.

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.

It's up to you which approach to choose.

CodePudding user response:

Lets take an example. You can use it when the below use cases are there

formControl: When you have very few (maybe one or two) independent field on your UI design, maybe an input. So there is no need for a form tag.

formGroup: When you have a form that has multiple inputs, dropdown, radio buttons. All of which you want to create a JSON object to pass in API.

formBuilder: When you have a dynamic form. for e.g, there are address bar inputs. Users can add as many input bars as by clicking on the 'Add new line' button. That time you can utilize creating dynamic formControls.

All of them give you an option to semantically create a group together, otherwise, all of this can be achieved just with formControl as well.

Hope you can relate to these usecases

  • Related