Creating FormGroup inside FormGroup in Angular

By Arvind Rai, September 20, 2022
On this page we will learn creating nested FormGroup in our Angular application. In nested FormGroup, we create FormGroup inside FormGroup. A FormGroup tracks the value and validity state of a group of FormControl instances.
In our example, we are creating FormGroup using FormBuilder.
Find the TypeScript code.
teamForm = this.formBuilder.group({
	teamLead: this.formBuilder.group({
		empName: ['', Validators.required],
		age: ['', [Validators.required, Validators.min(18)]],
		city: ['', Validators.required]
	}),
	------
}); 
Use formGroupName to create nested FormGroup in HTML template. Find the HTML code.
<div formGroupName="teamLead" class="employee"> 
  <b>Team Lead:</b> 
  <p>Name  : <input formControlName="empName">
	<label *ngIf="teamLead.get('empName')?.hasError('required')" class="error">
	  Name required. </label>
	</p>
  <p>Age : <input formControlName="age">
	<label *ngIf="teamLead.get('age')?.hasError('required')" class="error">
	  Age required. </label>
	<label *ngIf="teamLead.get('age')?.hasError('min')" class="error">
		Minimum age is 18. </label>
  </p>
  <p>City : <input formControlName="city">
	<label *ngIf="teamLead.get('city')?.hasError('required')" class="error">
	  City required. </label>
  </p>
</div> 
Now we will provide complete example.

Technologies Used

Find the technologies being used in our example.
1. Angular 13.1.0
2. Node.js 12.20.0
3. NPM 8.2.0

Complete Example

team-management.component.html
<h3>Create New Team</h3>
<div class="team">
  <form [formGroup]="teamForm" (ngSubmit)="onFormSubmit()">
    <p><b>Team Name : </b> <input formControlName="teamName">
      <label *ngIf="teamName?.hasError('required')" class="error">
        Team name required. </label>
    </p>
    <p><b>No. of Emp : </b> <input formControlName="noOfEmp">
      <label *ngIf="teamName?.hasError('required')" class="error">
        No. of Emp required. </label>
    </p>
    <div formGroupName="teamLead" class="employee"> 
      <b>Team Lead:</b> 
      <p>Name  : <input formControlName="empName">
        <label *ngIf="teamLead.get('empName')?.hasError('required')" class="error">
          Name required. </label>
        </p>
      <p>Age : <input formControlName="age">
        <label *ngIf="teamLead.get('age')?.hasError('required')" class="error">
          Age required. </label>
        <label *ngIf="teamLead.get('age')?.hasError('min')" class="error">
            Minimum age is 18. </label>
      </p>
      <p>City : <input formControlName="city">
        <label *ngIf="teamLead.get('city')?.hasError('required')" class="error">
          City required. </label>
      </p>
    </div>
    <div formGroupName="department" class="employee"> 
      <b>Department:</b> 
      <p>Department Head : <input formControlName="deptHead">
        <label *ngIf="department.get('deptHead')?.hasError('required')" class="error">
          Department Head required. </label>
      </p>
      <p>Department Name : <input formControlName="deptName">
        <label *ngIf="department.get('deptName')?.hasError('required')" class="error">
          Department Name required. </label>
      </p>
    </div>
    <button>SUBMIT</button>
  </form>
</div> 
team-management.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators, FormBuilder, FormGroup } from '@angular/forms';
import { TeamManagementService } from './team-management.service';

@Component({
	selector: 'app-team',
	templateUrl: './team-management.component.html'
})
export class TeamManagementComponent implements OnInit {
	constructor(
		private formBuilder: FormBuilder,
		private teamMngService: TeamManagementService) {
	}
	ngOnInit() {
	}
	teamForm = this.formBuilder.group({
		teamName: ['', Validators.required],
		noOfEmp: ['', Validators.required],
		teamLead: this.formBuilder.group({
			empName: ['', Validators.required],
			age: ['', [Validators.required, Validators.min(18)]],
			city: ['', Validators.required]
		}),
		department: this.formBuilder.group({
			deptHead: ['', Validators.required],
			deptName: ['', Validators.required]
		})
	});
	get teamName() {
		return this.teamForm.get('teamName') as FormControl;
	}
	get noOfEmp() {
		return this.teamForm.get('noOfEmp') as FormControl;
	}
	get teamLead() {
		return this.teamForm.get('teamLead') as FormGroup;
	}
	get department() {
		return this.teamForm.get('department') as FormGroup;
	}
	onFormSubmit() {
		if (this.teamForm.valid) {
		  this.teamMngService.saveTeam(this.teamForm.value);
	          this.teamForm.reset();
		}
	}
} 
team-management.service.ts
import { Injectable } from '@angular/core';
import { Team } from './team';
@Injectable()
export class TeamManagementService {
	saveTeam(team: Team) {
		console.log('------------TEAM------------');
		console.log('Team Name: ' + team.teamName);
		console.log('Team Size: ' + team.noOfEmp);
		console.log('----- Team Lead -----');
		console.log('Emp Name: ' + team.teamLead.empName);
		console.log('Emp Age: ' + team.teamLead.age);
		console.log('Emp City: ' + team.teamLead.city);
		console.log('----------department---------');
		console.log('Department Head: ' + team.department.deptHead);
		console.log('Department Name: ' + team.department.deptName);
	}
} 
team.ts
import { Department } from "./department";
import { Employee } from "./employee";
export interface Team {
	teamName: string;
	noOfEmp: number;
	teamLead: Employee;
	department: Department;
}
 
employee.ts
export interface Employee {
	empName: string;
	age: number;
	city: string;
} 
department.ts
export interface Department {
	deptHead: string; 
	deptName: string;
} 
app.component.ts
import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
           <app-team></app-team>
          `
})
export class AppComponent {
} 
styles.css
.team {
	border: 3px solid black;
	width: 500px;
}
.employee {
	border: 2px solid blue;
	width: 480px;
}
.error{
        color: red;
} 
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { TeamManagementComponent } from './team-management.component';
import { TeamManagementService } from './team-management.service';

@NgModule({
      imports: [
            BrowserModule,
            ReactiveFormsModule
      ],
      declarations: [
            AppComponent,
            TeamManagementComponent
      ],
      providers: [
            TeamManagementService
      ],
      bootstrap: [
            AppComponent
      ]
})
export class AppModule { } 

Run Application

To run the application, find the steps.
1. Download source code using download link given below on this page.
2. Use downloaded src in your Angular CLI application. To install Angular CLI, find the link.
3. Run ng serve using command prompt.
4. Access the URL http://localhost:4200
Find the print screen of the output.
Creating FormGroup inside FormGroup in Angular

Reference

FormGroup

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us