# Different methods of Form Array in Angular

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**

![Screenshot from 2022-08-25 15-09-18.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661420415833/F0UqLPc4W.png align="left")

**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**

![Screenshot from 2022-08-25 14-49-03.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661419424143/IHSFtcack.png align="left")

FormArrays are not only dynamic but they also provide different methods which are very useful in managing form.
  
Some of these methods are -

- push()
- clear()
- length
- at()
- removeAt()

### Creating FormArray

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**

![Screenshot from 2022-08-25 14-49-15.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661419375463/x6y1SRexh.png align="left")

 ### 1. push(control: AbstractControl): void

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**

![Screenshot from 2022-08-25 14-49-59.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661419490349/yesChRrAU.png align="left")

### 2. insert(index: number, controls: AbstractControl)

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**

![Screenshot from 2022-08-25 14-50-30.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661419558731/UVimTcU99.png align="left")

### 3. removeAt(index: number): void

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**

![Screenshot from 2022-08-25 14-50-34.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661419596987/0U2G2q_pz.png align="left")

**AbstractControl** at position 0 with values *firstName* and *lastName* as *"Yogesh"* and *"Kumar"* respectively, has been removed from the **FormArray**.

### 4. at(index: number)

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**

![Screenshot from 2022-08-25 15-01-39.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661419958187/iLIawz4CQ.png align="left")

### 5. length: number

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**

![Screenshot from 2022-08-25 15-03-35.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661420063571/-RlyjyX1y.png align="left")

### 6. clear(): void

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**

![Screenshot from 2022-08-25 15-06-08.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1661420215342/Eig1O_ifS.png align="left")

 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**









