FormBuilder In Reactive Forms

FormBuilder In Reactive Forms

In this article, we will learn about the how to use the FormBuilder to create a Form and add validation criteria. The Angular FormBuilder API simplifies the creation of reactive forms. FormGroups, nested FormGroups, FormArrays, and FormControls are all simple to add. It also enables us to configure the Validation rules for each control.

We recommend learning how to develop reactive forms if you're new to Reactive Forms.

What is FormBuilder

The FormBuilder is an Angular utility API for creating forms. It provides shortcuts for creating FormControl, FormGroup, and FormArray instances. It cuts down on the amount of code needed to create complex forms.

How to use FormBuilder

Import & inject FormBuilder API

To use the FormBuilder, we must first import it in our component.

  1. import { FormBuilder } from '@angular/forms'

 Following that, we must inject it into our component class.
  1. constructor(private formBuilder: FormBuilder) {
  2. }

Finally, construct the FormModel using the group, array, and control methods.

FormGroup

To create the Form Group, we use the group method. As a key-value pair, we supply the group method a list of Form Controls, a Form Array, or another Form Group. The name of the FormControlFormGroup, or FormArray is the key. The control's configuration is the value.

We've added six form controls to the example below. The initial value, which we set to empty string, is the first argument to the FormControl.
  1. this.contactForm = this.formBuilder.group({
  2. firstname: [''],
  3. lastname: [''],
  4. email: [''],
  5. gender: [''],
  6. isMarried: [''],
  7. country: [''],
  8. });

Nested FormGroup

It's exactly as simple to make a Nested FormGroup. As demonstrated below, use the formbuilder.group method.
  1. this.contactForm = this.formBuilder.group({
  2. firstname: [''],
  3. lastname: [''],
  4. email: [''],
  5. gender: [''],
  6. isMarried: [''],
  7. country: [''],
  8. address: this.formBuilder.group({
  9. city: [''],
  10. street: [''],
  11. pincode: ['']
  12. })
  13. })

Validations

The list of sync validators is the FormControl second argument. The example below demonstrates how to add validators.
  1. this.contactForm = this.formBuilder.group({
  2. firstname: ['', [Validators.required, Validators.minLength(10)]],
  3. lastname: ['', [Validators.required, Validators.maxLength(15), Validators.pattern("^[a-zA-Z]+$")]],
  4. email: ['', [Validators.required, Validators.email]],
  5. gender: ['', [Validators.required]],
  6. isMarried: ['', [Validators.required]],
  7. country: ['', [Validators.required]],
  8. address: this.formBuilder.group({
  9. city: ['', [Validators.required]],
  10. street: ['', [Validators.required]],
  11. pincode: ['', [Validators.required]],
  12. })
  13. });

Example of FormBuilder

The Angular Reactive Forms article taught us how to create reactive forms.

Open the app.component.ts file and add the following code:
  1. import { Component, ViewChild, ElementRef } from '@angular/core';
  2. import { FormGroup, FormControl, Validators } from '@angular/forms'
  3. import { FormBuilder } from '@angular/forms'
  4. import { groupBy } from 'rxjs/internal/operators/groupBy';
  5. @Component({
  6. selector: 'app-root',
  7. templateUrl: './app.component.html',
  8. styleUrls: ['./app.component.css']
  9. })
  10. export class AppComponent {
  11. title = 'Angular Reactive forms';
  12. contactForm;
  13. constructor(private formBuilder: FormBuilder) {
  14. // this.contactForm = this.formBuilder.group({
  15. // firstname: [''],
  16. // lastname: [''],
  17. // email: [''],
  18. // gender: [''],
  19. // isMarried: [''],
  20. // country: [''],
  21. // });
  22. // this.contactForm = this.formBuilder.group({
  23. // firstname: [''],
  24. // lastname: [''],
  25. // email: [''],
  26. // gender: [''],
  27. // isMarried: [''],
  28. // country: [''],
  29. // address: this.formBuilder.group({
  30. // city: [''],
  31. // street: [''],
  32. // pincode: ['']
  33. // })
  34. // });
  35. this.contactForm = this.formBuilder.group({
  36. firstname: ['', [Validators.required, Validators.minLength(10)]],
  37. lastname: ['', [Validators.required, Validators.maxLength(15), Validators.pattern("^[a-zA-Z]+$")]],
  38. email: ['', [Validators.required, Validators.email]],
  39. gender: ['', [Validators.required]],
  40. isMarried: ['', [Validators.required]],
  41. country: ['', [Validators.required]],
  42. address: this.formBuilder.group({
  43. city: ['', [Validators.required]],
  44. street: ['', [Validators.required]],
  45. pincode: ['', [Validators.required]],
  46. })
  47. });
  48. }
  49. get firstname() {
  50. return this.contactForm.get('firstname');
  51. }
  52. get lastname() {
  53. return this.contactForm.get('lastname');
  54. }
  55. get email() {
  56. return this.contactForm.get('email');
  57. }
  58. get gender() {
  59. return this.contactForm.get('gender');
  60. }
  61. get isMarried() {
  62. return this.contactForm.get('isMarried');
  63. }
  64. get country() {
  65. return this.contactForm.get('country');
  66. }
  67. get city() {
  68. return this.contactForm.get("address").get('city');
  69. }
  70. get street() {
  71. return this.contactForm.get("address").get('street');
  72. }
  73. get pincode() {
  74. return this.contactForm.get("address").get('pincode');
  75. }
  76. countryList: country[] = [
  77. new country("1", "India"),
  78. new country('2', 'USA'),
  79. new country('3', 'England')
  80. ];
  81. onSubmit() {
  82. console.log(this.contactForm.value);
  83. }
  84. }
  85. export class country {
  86. id: string;
  87. name: string;
  88. constructor(id: string, name: string) {
  89. this.id = id;
  90. this.name = name;
  91. }
  92. }

Now, open the app.component.html file and add the following code:
  1. <div style="float: left; width:50%;">
  2. <form [formGroup]="contactForm" (ngSubmit)="onSubmit()" novalidate>
  3. <p>
  4. <label for="firstname">First Name </label>
  5. <input type="text" id="firstname" name="firstname" formControlName="firstname">
  6. </p>
  7. <div
  8. *ngIf="!firstname?.valid && (firstname?.dirty ||firstname?.touched)">
  9. <div [hidden]="!firstname.errors.required">
  10. First Name is required
  11. </div>
  12. <div [hidden]="!firstname.errors.minlength">
  13. Min Length is 10
  14. </div>
  15. </div>
  16. <p>
  17. <label for="lastname">Last Name </label>
  18. <input type="text" id="lastname" name="lastname" formControlName="lastname">
  19. </p>
  20. <div *ngIf="!lastname.valid && (lastname.dirty ||lastname.touched)">
  21. <div [hidden]="!lastname.errors.pattern">
  22. Only characters are allowed
  23. </div>
  24. <div [hidden]="!lastname.errors.maxLength">
  25. Max length allowed is {{lastname.errors.maxlength?.requiredLength}}
  26. </div>
  27. <div [hidden]="!lastname.errors.required">
  28. Last Name is required
  29. </div>
  30. </div>
  31. <p>
  32. <label for="email">Email </label>
  33. <input type="text" id="email" name="email" formControlName="email">
  34. </p>
  35. <div *ngIf="!email.valid && (email.dirty ||email.touched)">
  36. <div [hidden]="!email.errors.required">
  37. email is required
  38. </div>
  39. <div [hidden]="!email.errors.email">
  40. invalid email id
  41. </div>
  42. </div>
  43. <p>
  44. <label for="gender">Geneder </label>
  45. <input type="radio" value="male" id="gender" name="gender" formControlName="gender"> Male
  46. <input type="radio" value="female" id="gender" name="gender" formControlName="gender"> Female
  47. </p>
  48. <div *ngIf="!gender.valid && (gender.dirty ||gender.touched)">
  49. <div [hidden]="!gender.errors.required">
  50. gender is required
  51. </div>
  52. </div>
  53. <p>
  54. <label for="isMarried">Married </label>
  55. <input type="checkbox" id="isMarried" name="isMarried" formControlName="isMarried">
  56. </p>
  57. <div *ngIf="!isMarried.valid && (isMarried.dirty ||isMarried.touched)">
  58. <div [hidden]="!isMarried.errors.required">
  59. isMarried is required
  60. </div>
  61. </div>
  62. <p>
  63. <label for="country">country </label>
  64. <select id="country" name="country" formControlName="country">
  65. <option [ngValue]="c.id" *ngFor="let c of countryList">
  66. {{c.name}}
  67. </option>
  68. </select>
  69. </p>
  70. <div *ngIf="!country.valid && (country.dirty ||country.touched)">
  71. <div [hidden]="!country.errors.required">
  72. country is required
  73. </div>
  74. </div>
  75. <div formGroupName="address">
  76. <div class="form-group">
  77. <label for="city">City</label>
  78. <input type="text" class="form-control" name="city" formControlName="city">
  79. </div>
  80. <div *ngIf="!city.valid && (city.dirty ||city.touched)">
  81. <div [hidden]="!city.errors.required">
  82. city is required
  83. </div>
  84. </div>
  85. <div class="form-group">
  86. <label for="street">Street</label>
  87. <input type="text" class="form-control" name="street" formControlName="street">
  88. </div>
  89. <div *ngIf="!street.valid && (street.dirty ||street.touched)">
  90. <div [hidden]="!street.errors.required">
  91. street is required
  92. </div>
  93. </div>
  94. <div class="form-group">
  95. <label for="pincode">Pin Code</label>
  96. <input type="text" class="form-control" name="pincode" formControlName="pincode">
  97. </div>
  98. <div *ngIf="!pincode.valid && (pincode.dirty ||pincode.touched)">
  99. <div [hidden]="!pincode.errors.required">
  100. pincode is required
  101. </div>
  102. </div>
  103. </div>
  104. <p>
  105. <button type="submit" [disabled]="!contactForm.valid">Submit</button>
  106. </p>
  107. </form>
  108. </div>
  109. <div style="float: right; width:50%;">
  110. <h3>Form Status</h3>
  111. <b>valid : </b>{{contactForm.valid}}
  112. <b>invalid : </b>{{contactForm.invalid}}
  113. <b>touched : </b>{{contactForm.touched}}
  114. <b>untouched : </b>{{contactForm.untouched}}
  115. <b>pristine : </b>{{contactForm.pristine}}
  116. <b>dirty : </b>{{contactForm.dirty}}
  117. <b>disabled : </b>{{contactForm.disabled}}
  118. <b>enabled : </b>{{contactForm.enabled}}
  119. <h3>Form Value</h3>
  120. {{contactForm.value |json}}
  121. </div>

Conclusion

The FormBuilder API makes it easy to interact with Angular reactive forms. To create our    FormModel, we can use the group, array, and control methods. FormBuilder cuts down on the amount of code needed to create sophisticated forms.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post