Home Angular Tutorials Angular formGroup addControl and removeControl

Angular formGroup addControl and removeControl

by aouidane.med.amine
54,767 views 15 min read

In this tutorial , we are going to learn how to use addControl and removeControl methods through formBuilder and formGroup in Angular.

Next ,we are going to see more advanced methods used to handle the formControl such as setControl  , contains and registerControl method that could be used through formGroup.

we must not forget that the control could be a simple formControl , formArray or even a formGroup.

Table of Contents

FormGroup addControl and removeControl Example

In our example we will have a form containing some information about the user.

the user can be married or single, if he is married we add the details of the partner.

So technically  we are going to add a new formGroup control to the existing formGroup depending on the selected option. Therefore , if the user is married , we add a new formGroup to add the details of the partner.

Initialize the formGroup

To use the formGroup methods , we need to have an existing formGroup, therefore , we need to initialize the formGroup using the formBuilder as a first step.

				
					   userForm: FormGroup = new FormGroup({});
 
  constructor(private formBuilder: FormBuilder) {
  }
  
    ngOnInit() {
    this.initializeForm();
  }

  initializeForm(): void {
    this.userForm = this.formBuilder.group({
      userName: ['', Validators.required],
      married: [false, Validators.required],
    });
  }
				
			

How to use the addControl method ?

If you check the syntax below , you can notice that the control parameter is an AbstractControl that means we could add a simple formControl , formGroup or a formArray using the same concept.

Syntax :

addControl(name: string, control: AbstractControl): void 

The addControl method allows us to add a new control with the necessary configuration such as the form Validations.

Since we have the user Form , now we can use the addControl method to add the details of the partner.

				
					
  addPartnerFormGroup(): void {

    const partnerFormGroup: FormGroup = this.formBuilder.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      age: ['', Validators.required],
      occupation: ['', Validators.required]
    })

    this.userForm.addControl('partner', partnerFormGroup);
  }
				
			

How to use the removeControl method ?

In the previous part of the tutorial , we have seen how to add a new control , now we are going to see how to remove the control.

Syntax :

removeControl(name: string): void 
				
					  // remove partner details formGroup control
  removePartnerFormGroup(): void {
      this.userForm.removeControl('partner');
  }
				
			

how to use the setControl method ?

The setControl allows us to replace the existing control , generally it is used to update the control configuration such as control validators.

Syntax :

setControl(name: string, control: AbstractControl): void 

How to use the contains() method ?

To secure our form , we need to check if the control that we are going to add already exists or not.

Syntax :

contains(controlName: string): Boolean 
				
					 // check if we have partner formGroup
  get hasPartnerFormGroup(): boolean {
    return this.userForm.contains('partner');
  }
				
			

Add the template

Now let’s see how to use the formGroup inside our template to bind correctly our controls.

				
					<form [formGroup]="userForm" (ngSubmit)="submit()">
  UserName: <input type="text" formControlName="userName">
  Married :
  <select formControlName="married"  (change)="onSelectChange()">
    <option [ngValue]="true">True</option>
    <option [ngValue]="false">false</option>
  </select>
  <br>

  <ng-container *ngIf="isMarried">
    <b>Partner :</b>
    <div formGroupName="partner">
      FirstName:
      <input type="text" formControlName="firstName">
      LastName:
      <input type="text" formControlName="lastName">
      Age:
      <input type="text" formControlName="age">
      Occupation:
      <input type="text" formControlName="occupation">
    </div>
  </ng-container>
  <button type="submit">Submit</button>
</form>

				
			

Full Typescript Example

app.component.ts

				
					import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  title = 'XperTuto.com : formGroup addControl and removeControl Example';

  userForm: FormGroup = new FormGroup({});

  partnerFormGroup: FormGroup = this.formBuilder.group({
    firstName: ['', Validators.required],
    lastName: ['', Validators.required],
    age: ['', Validators.required],
    occupation: ['', Validators.required]
  })

  constructor(private formBuilder: FormBuilder) {
  }

  ngOnInit() {
    this.initializeForm();
  }

  initializeForm(): void {
    this.userForm = this.formBuilder.group({
      userName: ['', Validators.required],
      married: [false, Validators.required],
    });
  }

  onSelectChange(): void {
    if (this.isMarried) {
      this.addPartnerFormGroup();
    } else {
      this.removePartnerFormGroup();
    }
  }

  // add partner details formGroup control
  addPartnerFormGroup(): void {
    if (!this.hasPartnerFormGroup) {
      this.userForm.addControl('partner', this.partnerFormGroup);
    }
  }

  // remove partner details formGroup control
  removePartnerFormGroup(): void {
    if (this.hasPartnerFormGroup) {
      this.userForm.removeControl('partner');
    }
  }
  // get married formControl value
  get isMarried(): boolean {
    return this.userForm?.get('married')?.value;
  }

  // get userName formControl value
  get userName(): string {
    return this.userForm.get('userName')?.value;
  }

 // check if we have partner formGroup
  get hasPartnerFormGroup(): boolean {
    return this.userForm.contains('partner');
  }

  submit(): void {
    console.log(this.userForm.value);
  }
}

				
			

References

Clone the Project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/formGroup_addControl_removeControl.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Forms :

Recapitulation

In this tutorial we have seen how to use formGroup addControl and removeControl methods and some other advanced formGroup methods through a real life example.

we have seen how to use :

  • addControl method to add new controls to existing formGroup
  • removeControl method to remove an existing control from a formGroup
  • setControl method ro replace an existing control
  • contains method to check if the control is already exist

I hope you enjoy reading this Tutorial.

You may also like