Angular Js

Explain FormGroup in Angular

Explain FormGroup in Angular

FormGroup in Angular

This Article helps you to Understand, FormGroup in Angular


Building Blocks of Angular Forms
Whether you use a template-driven or reactive forms strategy, the Angular Forms module has three building components.
FormControl, FormGroup and FormArray



FormGroup
A FormGroup is a group of FormControls. With the control name serving as the key, each FormControl acts as a property in a FormGroup.
There are frequently multiple fields on forms. It is useful to have an easy way to coordinate the Form controls.

Each of the aforementioned input fields is shown as a distinct FormControl. We would need to verify the legality of each and every FormControl if we wanted to validate our form. Imagine a form with numerous fields. To cycle over a large number of FormControls and verify their validity is laborious.

This problem is resolved by FormGroup by offering a wrapper interface for a set of FormControls.Each child FormControl's state is tracked by a FormGroup, which compiles the values into a single object. each control name serving as the key



import { Component, OnInit } from "@angular/core";
import { FormArray, FormControl, FormGroup, Validators } from "@angular/forms";
import { Observable } from "rxjs/Observable";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
  signupForm: FormGroup;

  constructor() {}

  ngOnInit() {

//Define FormGroup
    this.signupForm = new FormGroup({
      userData: new FormGroup({
        username: new FormControl(null, [Validators.required,this.forbiddenNames.bind(this),]),
        email: new FormControl(null, Validators.required, Validators.email], this.forbiddenEmails),
      }),
      gender: new FormControl("male")   
    });


//Assign Default Value
    this.signupForm.setValue({
      userData: {
        username: "Max",
        email: "max@test.com",
      },
      gender: "male"     
    });

    this.signupForm.patchValue({
      userData: {
        username: "Deepak",
      },
    });
  }

  onSubmit() {
    console.log(this.signupForm);
    this.signupForm.reset();
  }

 

  forbiddenNames(control: FormControl): { [s: string]: boolean } {
    if (this.forbiddenUsernames.indexOf(control.value) !== -1) {
      return { nameIsForbidden: true };
    }
    return null;
  }

  forbiddenEmails(control: FormControl): Promise<any> | Observable<any> {
    const promise = new Promise<any>((resolve, reject) => {
      setTimeout(() => {
        if (control.value === "test@test.com") {
          resolve({ emailIsForbidden: true });
        } else {
          resolve(null);
        }
      }, 1500);
    });
    return promise;
  }
}



//Can also do validation at TS level after submission inside onSubmit() Method
this.signupForm.userData.username.errors     // returns the list of errors
this.signupForm.userData.username.dirty      // true if the value of one of the child control has changed (dirty)
this.signupForm.userData.username.touched    // true if one of the child control is touched
this.signupForm.userData.username.valid      // true if all the child controls passed the validation




Map FormGroup in Template


//Map FormControl in Template
<div class="container">
  <div class="row">
    <div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
      <form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
        <div formGroupName="userData">
          <div class="form-group">
            <label for="username">Username</label>
            <input type="text" id="username"formControlName="username" class="form-control"/>
            <span *ngIf=" !signupForm.get('userData.username').valid &&
signupForm.get('userData.username').touched" class="help-block">
            <span *ngIf=" signupForm.get('userData.username').errors['nameIsForbidden']">
This name is invalid!
</span>
            <span *ngIf="signupForm.get('userData.username').errors['required']">
                This field is required!
</span>           
          </div>
          <div class="form-group">
            <label for="email">email</label>
            <input type="text" id="email" formControlName="email" class="form-control"/>
            <span  *ngIf="!signupForm.get('userData.email').valid && signupForm.get('userData.email').touched"
              class="help-block">Please enter a valid email!
</span>
          </div>
        </div>
        <div class="radio" *ngFor="let gender of genders">
          <label>
            <input type="radio" formControlName="gender" [value]="gender" />{{gender}}
          </label>
        </div>      

        <span *ngIf="!signupForm.valid && signupForm.touched" class="help-block">Please enter valid data!</span>
        <button class="btn btn-primary" type="submit">Submit</button>
      </form>
    </div>
  </div>
</div>







Validate in TS file Itself


import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
   selector: 'app-form-group',
   templateUrl: 'formgroup.component.html',
   styleUrls: ['formgroup.component.css']
})
export class FormGroupDemoComponent {
  usrNameChanges: string;
  usrNameStatus: string;
  userForm = new FormGroup({
  name: new FormControl('Mahesh', Validators.maxLength(10)),
  age: new FormControl(20, Validators.required),
  city: new FormControl(),
  country: new FormControl()
  });


  get userName(): any {
        return this.userForm.get('name');
  }


  onFormSubmit(): void {
  console.log('Name:' + this.userForm.get('name').value);
  console.log('Age:' + this.userForm.get('age').value);
  console.log('City:' + this.userForm.get('city').value);
  console.log('Country:' + this.userForm.get('country').value);
  }

  setDefaultValue() {
    this.userForm.setValue({name: 'Deepak Talwar', age: 30, city: '', country: ''});
  }
}





<h3> Using FormControl with FormGroup </h3>
<div>
 <form [formGroup]="userForm" (ngSubmit)="onFormSubmit()">
  <div>
    Name: <input formControlName="name"  placeholder="Enter Name">
  <label *ngIf="userName.invalid" [ngClass] = "'error'"> Name is too long. </label>
  </div>
  <div>
    Age: <input formControlName="age"  placeholder="Enter Age">
  <label *ngIf="userForm.get('age').invalid" [ngClass] = "'error'"> Age is required. </label>
  </div>
  <div>
    City: <input formControlName="city"  placeholder="Enter City">
  </div>
  <div>
    Country: <input formControlName="country" placeholder="Enter Country">
  </div>
  <div>
    <button type="submit">Submit</button>
    <button type="button" (click) = "setDefaultValue()">Set Default</button>
  </div>
 </form>
<div>





Related Post

About Us

Community of IT Professionals

A Complete IT knowledgebase for any kind of Software Language, Development, Programming, Coding, Designing, Networking, Hardware and Digital Marketing.

Instagram