• by Dinuka Ekanayake
  • Software Engineer

FormGroup and FormBuilder in Angular

Introduction to FormGroup

Many model controllers use the FromGroup to bind under a single form. angular FormGroup class is more useful when there are many fields of the form and need to tracks the value & validity of these fields.

Usage of FormGroup

Add the form modules metadata to the module class.

module.ts

// other imports ...
import { FormsModule ,ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule,
    FormsModule
  ],
})
export class AppModule { }
}

Create an instance of FormGroup in the component class then create a property named pocForm, and set the property to a new form group instance. To initialize the form group, provide the constructor with an object of named keys mapped to their control.

component.ts

 
import { FormBuilder , Validators } from '@angular/forms';

constructor(private fb: FormBuilder) { }

 pocForm = this.fb.group({

    firstName  : ['' , [Validators.required]],
    lastName   : ['' , [Validators.required]],
    nicNumber  : ['' , [Validators.required]]

  });

To bind form group to template need to use [formGroup] directive with form controllers.

component.html

<form [formGroup]="pocForm"  (ngSubmit)="onSubmit(pocForm)">
      <mat-form-field >
         <mat-label>First Name</mat-label>
         <input matInput formControlName ="firstName">
      </mat-form-field>
      <mat-form-field >
         <mat-label>Last Name</mat-label>
         <input matInput formControlName ="lastName">
      </mat-form-field>   
      <mat-form-field >
         <mat-label>Nic</mat-label>
         <input matInput formControlName ="nicNumber">
      </mat-form-field>   
      <button mat-flat-button   [disabled]="pocForm.invalid" 
       type="submit"  >Submit</button>
</form>
 
Patch values to form

patchValue() values ​​are used to set values controllers in formGroup.

component.ts

 patch(){
    this.pocForm.patchValue({
      firstName: 'dev'
    })
  }
 
Access the values

Using form controllers can access the form values in here show access the value of firstName.

component.ts

 
 fValueName(){
    this.pocForm.controls['firstName'].value;
  }
 
Display required messages

There are many ways to display warning messages in angular. In here listen to the form controller status and display the error message.

component.ts

 get f(){
    return this.pocForm.controls;
  }

component.html

  <mat-form-field>
     <mat-label>First Name</mat-label>
     <input type="text" matInput formControlName="firstName">
        <div  class="errorMessage" *ngIf="f.firstName.invalid 
              && (f.firstName.dirty || f.firstName.touched)">
                   <div *ngIf="f.firstName.errors?.required">
                   First Name Required
                  </div>  
        </div>
     </mat-form-field>
 
Submit the from

To submit form details use ng event binding.

component.ts

onSubmit(form: any) {
    if(this.pocForm.valid){
    console.log('Your form data : ', form.value);
    }
  }

 

Git Repository : https://github.com/darshana991/angularForms

Visit us on