Angular FormGroup vs FormBuilder




Asked on November 03, 2023
What is difference between FormGroup and FormBuilder in Angular application?


Replied on November 07, 2023
A. FormGroup

FormGroup tracks value and validity state of a group of FormControl instances. It is used to create HTML form. Each element of the form will bind to a FormControl. We can also use to combine some elements within the form as nested FormGroup.

Find the steps to bind FormGroup with a HTML form.

1. Create an instance of FormGroup containing some FormControl.

teamForm = new FormGroup({   
   name: new FormControl('', [Validators.required]),
   managerName:  new FormControl()
});


Each FormControl represents a HTML form element.

<form [formGroup]="teamForm" (ngSubmit)="onFormSubmit()">
    <p>Team Name : <input formControlName="name">
    <p>Manager Name : <input formControlName="managerName"></p>
</form>

B. FormBuilder

The FormBuilder shortens creating instances of a FormControlFormGroup, or FormArray. The methods of FormBuilder are group(), control() and array() .

1. group() creates FormGroup
2. control() 
creates FormControl
3. array() creates  FormArray

Find the example.

constructor(private formBuilder: FormBuilder) { }
teamForm = this.formBuilder.group({
   name: ['', Validators.required ],
   managerName: '',
});


HTML code will be same.

<form [formGroup]="teamForm" (ngSubmit)="onFormSubmit()">
    <p>Team Name : <input formControlName="name">
    <p>Manager Name : <input formControlName="managerName"></p>
</form>




Replied on November 07, 2023
Thanks.

Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us