I have following form. arr is a list of FormBuilder.
  get arr() {
    return this.form.get('arr') as FormArray;
  }
  this.form = this.fb.group({
      id: this.fb.control(''),
      name: this.fb.control('', Validators.required),
      arr: this.fb.array([], Validators.minLength(1)),
    });
  public removeArr(idx: number) {
    this.arr.removeAt(0);
  }
As you can see this.arr.removeAt(0), I am trying to remove first arr from the list, but it always removes the last element. Even I change it to something else e.g this.arr.removeAt(2), instead of removing the third element it removes the last element.
How can I remove any element given by idx instead of always removing the last element.
Note:
Looks like the problem is related to the trackby function.
<form *ngIf="form" [formGroup]="form">
  <mat-form-field appearance="outline">
    <mat-label>Name</mat-label>
    <input type="text" matInput formControlName="name" required />
  </mat-form-field>
   <div
        class="arr-row"
        *ngFor="let control of arrControls; let i = index; trackBy: trackByIndex"
        [formGroupName]="i"
      >
        <mat-form-field appearance="outline">
          <mat-label>Name</mat-label>
          <input type="text" matInput formControlName="name" required />
        </mat-form-field>
        <button mat-icon-button type="button" (click)="removeArr(i)">
          <mat-icon>delete</mat-icon>
        </button>
   </div>
</form>
   trackByIndex: TrackByFunction<FormControl> = (index, _) => index;
If I change trackby function to
   trackByIndex: TrackByFunction<FormControl> = (index, v) => v.value.id;
Then it works but not all of the elements has id, so I can not use id here.
Had same issue, solution was to track something meaningful and unique in *ngFor, insead of index:
@for (article of articles(); track article.id; let index = $index)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With