最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular .removeAt(i) at FormArray does not update in DOM - Angular - Stack Overflow

programmeradmin1浏览0评论

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: './appponent.html',
  styleUrls: ['./appponent.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>

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>

Share Improve this question edited Oct 30, 2018 at 1:40 caricature asked Oct 30, 2018 at 1:10 caricaturecaricature 1771 gold badge2 silver badges11 bronze badges 13
  • Could you please share the code? – Jameel Moideen Commented Oct 30, 2018 at 1:34
  • @NinjaJami added the code :D – caricature Commented Oct 30, 2018 at 1:40
  • strange ... i copy-pasted your code in StackBlitz and it works fine: stackblitz.com/edit/angular-stackoverflow-53056007 ... is there something else you forgot to share? – j3ff Commented Oct 30, 2018 at 2:32
  • @j3ff i copied the code as is and the adding works for me but the removing doesn't. that's what got me puzzled. – caricature Commented Oct 30, 2018 at 2:50
  • @caricature did you try to run the stackblitz shared by j3ff ? It's working in that sample. – Jameel Moideen Commented Oct 30, 2018 at 2:58
 |  Show 8 more comments

4 Answers 4

Reset to default 8

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.

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`

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()

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

发布评论

评论列表(0)

  1. 暂无评论