Different methods of Form Array in Angular
Introduction
FormArray is one of the four fundamental building blocks used to define forms in Angular, along with FormControl , FormGroup , and FormRecord . Further ...
You might already be familiar with angular's FormGroup but in this article we will discuss about FormArray and where it can be used.
When we have predefined number of fields for any form then we can use FormGroup but what if we need to construct a form that is more dynamic in nature i.e., we may come across some situation where we will be removing or adding fields much more frequently.
Let’s say we have to create a form for each and every student admitted in a particular class. On the very first day we need to store the data of single student only, which can easily be done using FormGroup but on the second day, the number of students increased to 10 . In these types of scenario we will be using FormArray to add fields dynamically as the number of students will keep on changing in this case.
Let's look at the example of FormGroup and FormArray.
Example of a form using FormGroup
public studentForm: FormGroup;
public ngOnInit(): void {
this.studentForm = this.fb.group({
firstName1: [null, [Validators.required]],
LastName1: [null, [Validators.required]],
firstName2: [null, [Validators.required]],
LastName2: [null, [Validators.required]],
});
}
Output Example
Example of a form using FormArray
public studentForm: FormGroup;
public ngOnInit(): void {
this.studentForm = this.fb.group({
studentDetails: this.getFormArray()
});
}
private getFormArray() {
return this.fb.array([
{
firstName: [null, [Validators.required]],
lastName: [null, [Validators.required]]
},
{
firstName: [null, [Validators.required]],
lastName: [null, [Validators.required]]
}
]);
}
Output Example
FormArrays are not only dynamic but they also provide different methods which are very useful in managing form.
Some of these methods are -
First we will declare a FormGroup -
public classForm: FormGroup;
In the next step we will use FormBuilder to create FormArray -
constructor(private fb: FormBuilder) {}
Here, we are creating FormArray named as students -
public ngOnInit(): void {
this.classForm = this.fb.group({
students: this.fb.array([
this.getFormGroup('Yogesh', 'Kumar')
]),
});
}
public getFormGroup(fName: string, lName: string): FormGroup {
return this.fb.group({
firstName: [fName, [Validators.required]],
lastName: [lName, [Validators.required]],
});
}
Output Example
push() method adds new FormControl in a FormArray at the end. It takes AbstractControl as parameter and returns nothing.
We will be adding student’s first and last name using pushFormGroup() function.
public ngOnInit(): void {
this.pushFormGroup('Saundarya', 'Tyagi');
this.pushFormGroup('Meet', 'Kamal');
}
Now, getFormGroup() function will create a FormGroup as shown above and we will push it in the FormArray using push() method.
public pushFormGroup(fName: string, lName: string) {
const fa = this.classForm.get('students') as FormArray;
const fg = this.getFormGroup(fName, lName);
fa.push(fg);
}
Output Example
insert() method works differently then push() method of FormArray. It adds AbstractControl at specified index rather than adding it at the end. insert() method doesn’t return anything.
public ngOnInit(): void {
this.insertAt(1, 'Ankit', 'Saiyan');
}
public insertAt(i: number, fName: string, lName: string) {
const fa = this.classForm.get('students') as FormArray;
const fg = this.getFormGroup(fName, lName);
fa.insert(i, fg);
}
Output Example
removeAt() takes only index as parameter and removes AbstractControl from that specified index of FormArray.
Note: If index is greater than the length of the FormArray then removeAt() method will not generate any error.
public ngOnInit(): void {
this.removeAt(0);
}
public removeAt(i) {
const fa = this.classForm.get('students') as FormArray;
fa.removeAt(i);
}
Output Example
AbstractControl at position 0 with values firstName and lastName as "Yogesh" and "Kumar" respectively, has been removed from the FormArray.
at() method takes index as parameter and returns the AbstractControl of the FormArray at that index.
public ngOnInit(): void {
this.getControlAtIndex(0);
}
public getControlAtIndex(i) {
const fa = this.classForm.get('students') as FormArray;
const control = fa.at(i);
console.log(control);
return control;
}
Output Example
length method returns the current length of FormArray.
public ngOnInit(): void {
this.getFormLength();
}
public getFormLength() {
const fa = this.classForm.get('students') as FormArray;
const length = fa.length;
console.log(length);
return length;
}
Output Example
clear() method removes all the controls of a FormArray. It returns void.
public ngOnInit(): void {
this.clearForm();
}
public clearForm() {
const fa = this.classForm.get('students') as FormArray;
fa.clear();
console.log(fa);
}+
Output Example
In the console of the above example, we can see the length of the control array of FormGroup is 0.
Checkout our other blogs as well.
Happy Learning
Publication Date
2022-11-04
Category
Javascript
Author Name
Saundarya Tyagi
Read More Blogs!
At RemoteState, we believe in a collaborative and transparent approach to software development. Here, we'll walk you through our proven development process, designed to ensure successful project delivery and exceed your expectations.
Big data analytics is a revolutionary tool that can be used to improve healthcare outcomes by leveraging data-driven insights to enhance clinical decision-making, improve patient care and outcomes, and optimize resource utilization.
Fintech has emerged as a significant disruptor in the insurance industry, changing the way insurance companies operate, and providing more value to customers. Fintech has brought about digitalization, automation, and innovation, which have significantly impacted the insurance industry's landscape.
Request Free consultation
HA 08, RWA Society, Sector 104, Noida, UP, India - 201304
hi@remotestate.com
+91 7906414865
Get Directions