FormArray also groups the controls (FormControl) like FormGroup but in the form of an Array.
If we want to add FormControl dynamically we can use FormArray.
In FormArray we can add or remove a FormControl. So initially there is no FormControl or
there can be more number of FormControl when a control is added.
Unlike FormGroup a FormArray controls can be identified by index position instead of name.
FormArrayComponent
import { Component, OnInit } from '@angular/core';
import { FormGroup,FormArray,FormBuilder } from '@angular/forms'
@Component({
selector: 'app-reactiveform',
templateUrl: './reactiveform.component.html',
styleUrls: ['./reactiveform.component.scss']
})
export class ReactiveformComponent {
title = 'Reactive forms - FormArray';
reactiveForm: FormGroup;
constructor(private fb:FormBuilder) {
this.reactiveForm = this.fb.group({
jobDescriptions: this.fb.array([]) ,
});
}
get jobDescriptions() : FormArray {
console.log('Get Skills'+this.reactiveForm.get("jobDescriptions"));
return this.reactiveForm.get('jobDescriptions') as FormArray
}
jobDescription(): FormGroup {
return this.fb.group({
jd: '',
level: '',
})
}
addJD() {
this.jobDescriptions.push(this.jobDescription());
}
deleteJD(i:number) {
this.jobDescriptions.removeAt(i);
}
}
FormArrayHTMLTemplate
<div class="container">
<div class="row">
<form [formGroup]="reactiveForm" class="col-xs-3">
<b>Job Description</b> <br>
ABC is hiring for below skill sets. <br>
For Each JD the expertise level required are,<br>
L1 - Beginner<br>
L2 - Intermediate<br>
L3 - Advanced
<div formArrayName="jobDescriptions">
<div *ngFor="let jd of jobDescriptions.controls; let i=index">
<div [formGroupName]="i" class="mt-2">
JD {{i + 1}}
<input type="text" formControlName="jd" placeholder="Skill Description">
Level:
<input type="text" formControlName="level" class="mr-1">
<button (click)="deleteJD(i)">Delete</button>
</div>
</div>
</div>
</form>
</div>
<p class="mt-2">
<button type="button" (click)="addJD()">Create JD</button>
</p>
{{this.reactiveForm.value | json}}
</div>
On executing the above example you will see the below output. On Clicking addJD you can add new Job Descriptions.
FormArray methods setValue and patchValue will be discussed in next post.