1
2import { Component } from '@angular/core';
3 import { FormGroup, FormArray, FormBuilder } from '@angular/forms'
4
5
6@Component({
7 selector: 'app-root',
8 templateUrl: './app.component.html',
9 styleUrls: ['./app.component.css']
10})
11export class AppComponent {
12
13 title = 'Nested FormArray Example Add Form Fields Dynamically';
14
15 empForm:FormGroup;
16
17
18 constructor(private fb:FormBuilder) {
19
20 this.empForm=this.fb.group({
21 employees: this.fb.array([]) ,
22 })
23 }
24
25
26 employees(): FormArray {
27 return this.empForm.get("employees") as FormArray
28 }
29
30
31 newEmployee(): FormGroup {
32 return this.fb.group({
33 firstName: '',
34 lastName: '',
35 skills:this.fb.array([])
36 })
37 }
38
39
40 addEmployee() {
41 console.log("Adding a employee");
42 this.employees().push(this.newEmployee());
43 }
44
45
46 removeEmployee(empIndex:number) {
47 this.employees().removeAt(empIndex);
48 }
49
50
51 employeeSkills(empIndex:number) : FormArray {
52 return this.employees().at(empIndex).get("skills") as FormArray
53 }
54
55 newSkill(): FormGroup {
56 return this.fb.group({
57 skill: '',
58 exp: '',
59 })
60 }
61
62 addEmployeeSkill(empIndex:number) {
63 this.employeeSkills(empIndex).push(this.newSkill());
64 }
65
66 removeEmployeeSkill(empIndex:number,skillIndex:number) {
67 this.employeeSkills(empIndex).removeAt(skillIndex);
68 }
69
70 onSubmit() {
71 console.log(this.empForm.value);
72 }
73
74
75}
76
77
78export class country {
79 id: string;
80 name: string;
81
82 constructor(id: string, name: string) {
83 this.id = id;
84 this.name = name;
85 }
86}
87
88
89
90
1
2<h1>{{title}}</h1>
3
4<form [formGroup]="empForm" (ngSubmit)="onSubmit()">
5
6 <div formArrayName="employees">
7
8 <div *ngFor="let employee of employees().controls; let empIndex=index">
9
10 <div [formGroupName]="empIndex" style="border: 1px solid blue; padding: 10px; width: 600px; margin: 5px;">
11 {{empIndex}}
12 First Name :
13 <input type="text" formControlName="firstName">
14 Last Name:
15 <input type="text" formControlName="lastName">
16
17 <button (click)="removeEmployee(empIndex)">Remove</button>
18
19
20 <div formArrayName="skills">
21
22 <div *ngFor="let skill of employeeSkills(empIndex).controls; let skillIndex=index">
23
24
25
26 <div [formGroupName]="skillIndex">
27 {{skillIndex}}
28 Skill :
29 <input type="text" formControlName="skill">
30 Exp:
31 <input type="text" formControlName="exp">
32
33 <button (click)="removeEmployeeSkill(empIndex,skillIndex)">Remove</button>
34
35 </div>
36
37 </div>
38 <button type="button" (click)="addEmployeeSkill(empIndex)">Add Skill</button>
39 </div>
40
41
42 </div>
43
44 </div>
45 </div>
46
47 <p>
48 <button type="submit">Submit</button>
49 </p>
50
51</form>
52
53
54<p>
55 <button type="button" (click)="addEmployee()">Add Employee</button>
56</p>
57
58{{this.empForm.value | json}}
59
60