简体   繁体   English

为什么 patchValue 不能在有角度的 formArray 中工作?

[英]Why patchValue not working in formArray in angular?

I create a formArray inside form in angular.我在有角度的form中创建了一个formArray

When I patch object that has tasks with values as array, seems that this property is ignore and not set.当我修补具有值为数组的tasks对象时,似乎该属性被忽略且未设置。

as expected, the firstname is changed.正如预期的那样,名字已更改。 but the tasks not.但任务不是。 why?为什么?

I don't want to catch the specific element and use setValue or something similar, I just want to have an object and angular will investigate this object and match the values and the fields.我不想捕获特定元素并使用setValue或类似的东西,我只想拥有一个对象,angular 将调查此对象并匹配值和字段。

The code in stackblitz.com stackblitz.com 中的代码

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

@Component({
  selector: "my-app",
  template: `
    <form [formGroup]="profileForm">
      {{ profileForm.value | json }}

      <br /><br /><br />
      <label>
        First Name:
        <input type="text" formControlName="firstName" />
      </label>

      <label>
        Last Name:
        <input type="text" formControlName="lastName" />
      </label>

      <button type="button" (click)="clickme()">clickme</button>
    </form>
  `
})
export class AppComponent {
  profileForm = new FormGroup({
    firstName: new FormControl(""),
    lastName: new FormControl(""),
    tasks: new FormArray([])
  });

  clickme() {
    this.profileForm.patchValue({
      firstName: "foo",
      tasks: [false, true, false]
    });
  }
}

As stated in to the documentation :文档中所述

A FormArray :一个 FormArray :

Tracks the value and validity state of an array of FormControl, FormGroup or FormArray instances.

A FormArray is meant to be an array of controls, not of values. FormArray 是一个控件数组,而不是值数组。 You can only patchValues to existing formControls.您只能将值修补到现有的 formControls。

In your situation, if you want to patch [false, true, false] , you need to define your tasks FormArray as tasks: new FormArray([new FormControl(), new FormControl(), new FormControl()]) , so you have 3 controls ready to be populated.在你的情况下,如果你想修补[false, true, false] ,你需要将你的任务 FormArray 定义为tasks: new FormArray([new FormControl(), new FormControl(), new FormControl()]) ,所以你有 3 个控件可以填充。

Another solution would be to loop over your array to push a new FormControl with the value new FormControl(data[x]) for each item.另一种解决方案是循环遍历您的数组,为每个项目推送一个值为new FormControl(data[x])

const tasks = [true, false, true];

tasks.forEach(task => {
  this.profileForm.controls.tasks.push(new FormControl(task));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM