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 ?
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.
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 formGroupremoveControl
method to remove an existing control from a formGroupsetControl
method ro replace an existing controlcontains
method to check if the control is already exist
I hope you enjoy reading this Tutorial.