1

Like it says, I want to add an item to the middle of a FormArray. So, I have a FormArray and every FormArray item has a button to add a new FormArray item. However, it currently always adds it to the bottom. I want to add it right after the item that the button is clicked on.

<div *ngFor="let filter of filterArray; let i = index" [formGroupName]="i" >
    <ng-select [items]="items1" bindLabel="name" formControlName="fc1"></ng-select>
    <ng-select [items]="items2" bindLabel="name" formControlName="fc2"></ng-select>
    <input type="text" formControlName="value" placeholder="Value">
    <button type="button" (click)="addRow(i)">Add</button>
    <button type="button" (click)="removeRow(i)"><i class="bi bi-x"></i></button>
</div>

So, if there are three items in the array and I click the Add button on the second item it should add the item immediately after the second item, not at the end of the list. Since the FormArray isn't and actual array, the splice method doesn't work. Any relatively easy way to work with a form array like this?

1
  • can you share the .ts file to check the logic behind this
    – Zanda
    Commented Apr 15 at 3:31

1 Answer 1

0

For inserting, we can use the FormArray method insert.

addRow(index: number) {
  this.formArray.insert(index + 1, this.getGroup());
}

For removing, we can use the FormArray method removeAt.

removeRow(index: number) {
  this.formArray.removeAt(index);
}

Full Code:

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import {
  FormArray,
  FormControl,
  FormGroup,
  ReactiveFormsModule,
} from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
  selector: 'app-root',
  imports: [ReactiveFormsModule, CommonModule],
  template: `
  <form [formGroup]="form">
    <div formArrayName="test">
    <div *ngFor="let filter of filterArray; let i = index" [formGroupName]="i" >
        <input type="text" formControlName="value" placeholder="Value">
        <button type="button" (click)="addRow(i)">Add</button>
        <button type="button" (click)="removeRow(i)">Remove</button>
    </div>
    </div>
</form>
<br/>
{{form.value | json}}
  `,
})
export class App {
  form = new FormGroup({
    test: new FormArray([this.getGroup()]),
  });

  getGroup() {
    return new FormGroup({
      value: new FormControl(`${Math.random()}`),
    });
  }

  get formArray() {
    return this.form.get('test') as FormArray;
  }

  get filterArray() {
    return this.formArray.controls as Array<FormControl>;
  }

  addRow(index: number) {
    this.formArray.insert(index + 1, this.getGroup());
  }

  removeRow(index: number) {
    this.formArray.removeAt(index);
  }
}

bootstrapApplication(App);

Stackblitz Demo

1
  • @HisDivineShadow does this answer help you? Commented Apr 22 at 14:31

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.