FormGroup and FormBuilder in angular 
Tags: angular, javascript, webdev
Published: 2021-01-21 10:21:06


[Git Repository](https://github.com/darshana991/angularForms)

### Table Of Content
  * [Introduction to FormGroup](#chapter-1)
  * [Usage of FormGroup](#chapter-2)
  * [Patch values to form](#chapter-3)
  * [Access the values](#chapter-4)
  * [Display required messages](#chapter-5)
  * [Submit the form](#chapter-6)

### Introduction to FormGroup <a name="chapter-1"></a>

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  <a name="chapter-2"></a>
Add the form modules metadata to the module class. 

module.ts
```javascript
// 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
```javascript
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
```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 <a name="chapter-3"></a>
patchValue() values ​​are used to set values controllers in formGroup.

component.ts
```javascript
  patch(){
    this.pocForm.patchValue({
      firstName: 'dev'
    })
  }

```

### Access the values<a name="chapter-4"></a>
Using form controllers can access the form values in here show access the value of firstName.

component.ts
```javascript
  fValueName(){
    this.pocForm.controls['firstName'].value;
  }
```
### Display required messages <a name="chapter-5"></a>
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
```javascript
 get f(){
    return this.pocForm.controls;
  }
```
component.html
```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 <a name="chapter-6"></a>

To submit form details use ng event binding.

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