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

car*_*ure 7 javascript typescript angular angular-reactive-forms

我认为这是我的实现的问题,但从我提出的这个问题来看,我用于创建动态 FormArray 的代码似乎应该是功能性的。当我将它集成到我的项目中时,删除函数确实从 FormArray 中删除了元素,但它不会反映在界面中/不会从 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);
  }
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

小智 6

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

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

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);
}
Run Code Online (Sandbox Code Playgroud)

我希望它可以帮助将来遇到这个问题的人。


Ibs*_*ado 1

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

constructor(private _fb: FormBuilder, private appRef: ApplicationRef) {}
Run Code Online (Sandbox Code Playgroud)

并在removeFormInput中

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

查看 Angular 文档:API > @angular/core /ApplicationRef.tick()