6

I thought it was an issue with my implementation but seems that my code for creating dynamic FormArray should be functional based from this question I raised. When I integrate it to my project, the remove function does delete the element from the FormArray, but it does not reflect in the interface/ does not remove object from the DOM. What could be causing this?

import {
  Component,
  VERSION
} from '@angular/core';
import {
  FormGroup,
  FormControl,
  FormArray,
  Validators,
  FormBuilder
} from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  objectProps: any[];

  public dataObject = [{
      "label": "Name",
      "name": "name",
      "type": "text",
      "data": ""
    },
    {
      "label": "Contacts",
      "name": "contacts",
      "type": "inputarray",
      "array": []
    }
  ]
  form: FormGroup;

  constructor(private _fb: FormBuilder) {}

  ngOnInit() {

    const formGroup = {};
    for (let field of this.dataObject) {
      if (field.type == "inputarray") {
        console.log("THIS IS " + field.type)
        formGroup[field.name] = this._fb.array([''])
      } else {
        console.log("THIS IS " + field.type)
        formGroup[field.name] = new FormControl(field.data || '') //, this.mapValidators(field.validation));
      }
    }

    this.form = new FormGroup(formGroup);
  }

  addFormInput(field) {
    const form = new FormControl('');
    ( < FormArray > this.form.controls[field]).push(form);
  }

  removeFormInput(field, i) {
    ( < FormArray > this.form.controls[field]).removeAt(i);
  }
}
<form *ngIf="form" novalidate (ngSubmit)="onSubmit(form.value)" [formGroup]="form">
  <div *ngFor="let field of dataObject">
    <h4>{{field.label}}</h4>
    <div [ngSwitch]="field.type">
      <input *ngSwitchCase="'text'" [formControlName]="field.name" [id]="field.name" [type]="field.type" class="form-control">
      <div *ngSwitchCase="'inputarray'">
        <div formArrayName="{{field.name}}" [id]="field.name">
          <div *ngFor="let item of form.get(field.name).controls; let i = index;" class="array-line">
            <div>
              <input class="form-control" [formControlName]="i" [placeholder]="i">
            </div>
            <div>
              <button id="btn-remove" type="button" class="btn" (click)="removeFormInput(field.name, i)">x</button>
            </div>
          </div>
        </div>
        <div>
          <button id="btn-add" type="button" class="btn" (click)="addFormInput(field.name)">Add</button>
        </div>
      </div>
    </div>
  </div>
  <button type="submit" class="btn btn-danger btn-block" style="float: right; width:180px" [disabled]="!form.valid">Save</button>
caricature
  • 167
  • 1
  • 2
  • 11

4 Answers4

4

This is not a great solution but I solved my problem by manipulating value and after removing the control.

I simply moved the item that I wanted to remove to the end of the array and then I removed the last item.

removeItem(index: number): void {
  const value = this.formArray.value;

  this.formArray.setValue(
    value.slice(0, index).concat(
      value.slice(index + 1),
    ).concat(value[index]),
  );

  this.formArray.removeAt(value.length - 1);
}

I hope it helps someone struggling with this issue in the future.

Anurag A S
  • 725
  • 10
  • 23
oreo
  • 41
  • 2
  • normally trackBy function that returns item will solve this problem but I also had another problem that required trackBy to return the index of item so I have implemented Your solution which works just fine. – DanielWaw Mar 21 '22 at 11:04
1

Maybe you can try to force change detection using the reference to application. To do that inject the ApplicationRef in the constructor an call the tick(); on your removeFormInput method.

constructor(private _fb: FormBuilder, private appRef: ApplicationRef) {}

And in removeFormInput

removeFormInput(field, i) {
    (<FormArray>this.form.controls[field]).removeAt(i);
    this.appRef.tick();
}

Take a look at angular documentation: API > @angular/core /ApplicationRef.tick()

Ibson Machado
  • 143
  • 1
  • 6
  • After many unsuccessful attempts with `updateValueAndValidity()` this solved it. Thanks! Although I used the ChangeDetector `detectChanges()` - https://angular.io/api/core/ChangeDetectorRef#detectChanges – Paul G Oct 19 '21 at 21:39
0

replace below function, you are not removing the row object from 'dataObject'.

removeFormInput(field, i) {
    ( < FormArray > this.form.controls[field]).removeAt(i);
    this.dataObject.splice(this.dataObject.indexOf(field),1);
  }

Take a look here Add and Remove form items I build on stackblitz, for me its working fine, adding and removing items... Take a look.

working version

Ibson Machado
  • 143
  • 1
  • 6
Ajay Ojha
  • 380
  • 1
  • 3
  • 9
  • dataObject is an array of objects so I can't get the index with field :( – caricature Oct 30 '18 at 07:19
  • Sorry, my mistake. Check the edited code. I am getting index based on field. Second way is you pass the index from html also you just need to replace two lines in the html. lines are : (line number 2) - *ngFor="let field of dataObject; let rowIndex = index" and (line number 13) - (click)="removeFormInput(field.name, i,rowIndex)". pass this 'rowIndex' in array of splice method. Please let me know, if any confusion. – Ajay Ojha Oct 30 '18 at 07:21
  • splice isn't working for me either :( also using rowIndex isn't always ok because the counting will not be inline with the FormArray indices :( – caricature Oct 31 '18 at 06:18
  • I believe that will work. I am not getting you, where you see the problem. – Ajay Ojha Oct 31 '18 at 06:41
  • What you built on stackblitz does not work either. When you list down 0,1,2,3, then click `x` on `1`, the list would become: 0,1,2. When the question of the OP is asking for is that the list would become 0.2,3. – Rin Minase Jun 25 '19 at 07:22
  • @AjayOjha If I try your solution on my side, I get: Cannot assign to read only property '0' of object – Jerome2606 Apr 24 '20 at 06:59
0

I was facing this problem as well. The solution for me was to get rid of/fix the trackBy function in NgFor*. I think you need to introduce a proper trackBy function and it might solve your error.

sauce: How to use `trackBy` with `ngFor`

Anirudh Ramesh
  • 48
  • 4
  • 13