Home Angular Tutorials Angular formArray Example

Angular formArray Example

by aouidane.med.amine
39,213 views 25 min read

In this Angular tutorial, we are going to see an angular formArray example and explain it step by step to learn how to use it in simple or advanced use cases.

In our example we are going to create and delete dynamically multiples formControl.

Table of Contents

What is Angular formArray ?

angular formArray is a class provided when we use the reactive forms approach. This class allows us to add and manipulate multiple controls dynamically.

These controls could be a simple formControl , a formGroupor even a formArray

The advantage of the formArray is that the control is a part of an array , that means it is located by an index so we can add and delete any control swiftly since we know the control index.

Meanwhile the control in the formGroup is represented by a key-value pair and that makes it a static object , so it is complicated to add or delete controls related to the formGroup.

Angular formArray Example

import formArray

like any other angular class , to use it we need to import it in the component class.

In our case we are going to import the formArray class from the Angular Form Module.

				
					import {FormArray} from "@angular/forms";
				
			

import and use formBuilder and formGroup

To create the formArray we need to create our form model using the formBuilder and formGroup :

				
					import {Component, OnInit} from '@angular/core';
import {FormArray, FormBuilder, FormGroup} from "@angular/forms";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  title = 'XperTuto.com : FormArray Example';

  tagsForm: FormGroup = new FormGroup({});

  constructor(private formBuilder: FormBuilder) {
  }

  ngOnInit() {
    this.initializeForm();
  }

  initializeForm(): void {
    this.tagsForm = this.formBuilder.group({
      webSite: '',
      tags: this.formBuilder.array([]),
    });
  }
}
				
			

get formArray control

To get the formArray object, we do the same thing like any other control, nothing special !

				
					 get tags(): FormArray {
    return this.tagsForm.get("tags") as FormArray
  }
				
			

Add and remove dynamically control

The advantage of the formArray is that we manipulate a simple array , that means we can push and remove from an array, so the methods like push and removeAt are enough to handle that.

				
					  newTag(): FormGroup {
    return this.formBuilder.group({
      technologie: '',
      nb_tutorials: '',
    })
  }

  addTags(): void {
    this.tags.push(this.newTag());
  }

  removeTag(tagIndex: number): void {
    this.tags.removeAt(tagIndex);
  }
				
			

Build form template

Now to create the template we need to add our elements and bind them correctly.

  • [formGroup]=”tagsForm” used to bind the form to tagsForm model
  •  formControlName=”webSite” used to bind formControl value to the property in the formGroup
  • formArrayname=”tags” used to bind the formArray to the property in the fromGroup

Now let’s go further and loop the formArray in the template.

In our example the formArray contains a formGroup , that means we need to add the formGroupName directive to bind correctly each formGroup in the formArray

				
					<form [formGroup]="tagsForm" (ngSubmit)="submit()">
  WebSite: <input type="text" formControlName="webSite"><br>
  Tags:
  <div formArrayName="tags">
    <div *ngFor="let tag of tags.controls; let tagIndex=index">
      <div [formGroupName]="tagIndex">
        {{tagIndex}}
        technologie  :
        <input type="text" formControlName="technologie">
        nb_tutorials:
        <input type="text" formControlName="nb_tutorials">

        <button (click)="removeTag(tagIndex)">Remove</button>
      </div>
    </div>
  </div>

  <p>
    <button type="submit">Submit</button>
    <button type="button" (click)="addTags()">Add</button>
  </p>

</form>

				
			

get formArray value

Now we will get the formArray value as final step through the submit button

				
					  submit() {
    const formvalue = this.tagsForm.value;
    console.log(formvalue);
  }
				
			

References

Clone and Run the project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/angular-formArray-Example.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Forms :

Recapitulation

In this tutorial we have created a simple angular formArray example to learn how to use use the formArray to build a simple and complex forms.

we also seen how to add and remove dynamically controls using the formArray.

Finally we have seen how to implement the template and loop the formArray to add dynamically html elements and getting the fromArray values when we dispatch the submit button.

I hope you enjoy reading this Tutorial.

You may also like