DEV Community

Dinuka Darshana
Dinuka Darshana

Posted on • Edited on

FormGroup and FormBuilder in angular

Git Repository

Table Of Content

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 { }
}
Enter fullscreen mode Exit fullscreen mode

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]]

  });

Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Patch values to form

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

component.ts

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

Enter fullscreen mode Exit fullscreen mode

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;
  }
Enter fullscreen mode Exit fullscreen mode

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;
  }
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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);
    }
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
stevekent profile image
Info Comment hidden by post author - thread only accessible via permalink
steve-kent

I think you have a typo. In your ts the FormGroup object name is "profileForm". In the html it's "pocForm".
Also just noticed that in the text of the blog you said you were going to name it "myForm" I think.

Collapse
 
darshana991 profile image
Dinuka Darshana

It is fixed. Thanks for the notice.

Some comments have been hidden by the post's author - find out more