FormArray上的Angular .removeAt(i)在DOM中不更新-Angular

时间:2018-10-30 01:10:43

标签: javascript angular typescript angular-reactive-forms

我认为这与我的实现有关,但似乎我创建动态FormArray的代码应基于我提出的this question来起作用。当我将其集成到项目中时,remove函数会从FormArray中删除该元素,但是它不会反映在interface /中,也不会从DOM中删除对象。可能是什么原因造成的?

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>

3 个答案:

答案 0 :(得分:0)

也许您可以尝试使用对应用程序的引用来强制进行更改检测。为此,将 ApplicationRef 注入构造函数中,并在 removeFormInput 方法上调用 tick();

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

并在 removeFormInput

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

看看角度文档:API > @angular/core /ApplicationRef.tick()

答案 1 :(得分:0)

替换下面的函数,您没有从'dataObject'中删除行对象。

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

在这里看看Add and Remove form items,我基于stackblitz构建,对我来说它工作正常,可以添加和删除项目...看一看。

working version

答案 2 :(得分:0)

这不是一个很好的解决方案,但是我通过操纵值和删除控件后解决了我的问题。

我只是将要删除的项目移到了数组的末尾,然后删除了最后一个项目。

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);
}

我希望它可以帮助将来在这个问题上苦苦挣扎的人。