【问题标题】:Why patchValue not working in formArray in angular?为什么 patchValue 在 angular 中的 formArray 中不起作用?
【发布时间】:2020-10-12 20:39:36
【问题描述】:

我在 form 内以角度创建了一个 formArray。

当我修补具有 tasks 且值为数组的对象时,似乎此属性被忽略且未设置。

正如预期的那样,名字已更改。但任务不是。为什么?

我不想捕获特定元素并使用setValue 或类似的东西,我只想拥有一个对象,Angular 会调查这个对象并匹配值和字段。

The code in 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]
    });
  }
}

【问题讨论】:

标签: angular


【解决方案1】:

如documentation中所述:

一个表单数组:

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

FormArray 是一个控件数组,而不是值数组。 您只能将值修补到现有的 formControls。

在你的情况下,如果你想修补[false, true, false],你需要将你的任务FormArray定义为tasks: new FormArray([new FormControl(), new FormControl(), new FormControl()]),这样你就有3个控件可供填充。

另一种解决方案是循环遍历您的数组,为每个项目推送一个新的 FormControl,其值为 new FormControl(data[x])。

const tasks = [true, false, true];

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-19
    • 2021-07-04
    • 2017-05-18
    • 2017-10-11
    • 2018-12-20
    • 1970-01-01
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多