Home  >  Angular

Creating FormGroup inside FormArray in Angular

By Arvind Rai, September 18, 2022
On this page we will learn to create FormGroup inside FormArray in Angular application. The FormGroup tracks the value and validity state of a group of FormControl instances. The FormArray tracks the value and validity state of an array of FormControl, FormGroup or FormArray instances. Inside a FormArray, we can create FormControl, FormGroup or FormArray.
Here in our example, we will create FormGroup inside FormArray.
Find the TypeScript code.
teamForm = this.formBuilder.group({
	teamName: ['', Validators.required],
	employees: this.formBuilder.array([])
});
get employees() {
	return this.teamForm.get('employees') as FormArray;
}
addEmployeeControl() {
	const empGroup = this.formBuilder.group({
		empName: ['', Validators.required],
                age: ['', [Validators.required, Validators.min(18)]],
		city: ['', Validators.required]
	});
	this.employees.push(empGroup);
} 
Find the HTML code.
<div formArrayName="employees">
  <div *ngFor="let emp of employees.controls; let i = index" [formGroupName]="i" class="employee">
	<p> <b>Employee {{i + 1}} : </b> </p>
	<p> Name: <input formControlName="empName"> 
	  <label *ngIf="emp.get('empName')?.hasError('required')" class="error">
		Employee name required. </label>
	</p>
	<p> Age: <input formControlName="age">
	  <label *ngIf="emp.get('age')?.hasError('min')" class="error">
	   Minimum Age is 18. </label>
	  <label *ngIf="emp.get('age')?.hasError('required')" class="error">
		Age required. </label>        
	</p>
	<p> City: <input formControlName="city">
	  <label *ngIf="emp.get('city')?.hasError('required')" class="error">
		City required. </label>
	</p>
	<p> <button type="button" (click)="deleteEmployeeControl(i)">Delete</button> </p>
  </div>
</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.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormArray, Validators, FormBuilder } 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],
		employees: this.formBuilder.array([])
	});
	get teamName() {
		return this.teamForm.get('teamName') as FormControl;
	}
	get employees() {
		return this.teamForm.get('employees') as FormArray;
	}
	addEmployeeControl() {
		const empGroup = this.formBuilder.group({
			empName: ['', Validators.required],
			age: ['', [Validators.required, Validators.min(18)]],
			city: ['', Validators.required]
		});
		this.employees.push(empGroup);
	}
	deleteEmployeeControl(index: number) {
		this.employees.removeAt(index);
	}
	resetEmployees() {
		this.employees.reset();
	}
	clearEmployeeControls() {
		this.employees.clear();
	}
	onFormSubmit() {
		if (this.teamForm.valid) {
		  this.teamMngService.saveTeam(this.teamForm.value);
	       this.teamForm.reset();
		}
	}
} 
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">
      <br /><label *ngIf="teamName?.dirty && teamName?.hasError('required')" class="error">
        Team name required. </label>
    </p>
    <b> Employees in Team :</b><br><br>
    <div formArrayName="employees">
      <div *ngFor="let emp of employees.controls; let i = index" [formGroupName]="i" class="employee">
        <p> <b>Employee {{i + 1}} : </b> </p>
        <p> Name: <input formControlName="empName"> 
          <label *ngIf="emp.get('empName')?.hasError('required')" class="error">
            Employee name required. </label>
        </p>
        <p> Age: <input formControlName="age">
          <label *ngIf="emp.get('age')?.hasError('min')" class="error">
           Minimum Age is 18. </label>
          <label *ngIf="emp.get('age')?.hasError('required')" class="error">
            Age required. </label>        
        </p>
        <p> City: <input formControlName="city">
          <label *ngIf="emp.get('city')?.hasError('required')" class="error">
            City required. </label>
        </p>
        <p> <button type="button" (click)="deleteEmployeeControl(i)">Delete</button> </p>
      </div>
    </div>
    <button type="button" (click)="addEmployeeControl()">Add Employee</button><br />
    <button type="button" (click)="resetEmployees()">Reset Employees</button><br />
    <button type="button" (click)="clearEmployeeControls()">clear Employees</button><br /><br />
    <button>SUBMIT</button>
  </form>
</div> 
team.ts
import { Employee } from "./employee";
export interface Team {
	teamName: string;
	employees: Employee[];
} 
employee.ts
export interface Employee {
	empName: string;
	age: number;
	city: string;
} 
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('----- Employee Detail -----');
		for (let emp of team.employees) {
			console.log('Emp Name: ' + emp.empName);
			console.log('Emp Age: ' + emp.age);
			console.log('Emp City: ' + emp.city);
			console.log('-------------------');
		}
	}
} 
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: 450px;
}
.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 FormArray in Angular

References

FormGroup
FormArray

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI











©2022 concretepage.com | Privacy Policy | Contact Us