Angular2 patchValue将值推入数组

21

看起来像是Angular2的FormGroup.patchValue()无法将新元素推入数组中。

例如,像这样的一些东西:

ngOnInit() {

    this.form = this.formBuilder.group({
        animal: [''],
        school: this.formBuilder.group({
            name: [''],
        }),
        students: this.formBuilder.array([this.formBuilder.control('Bob')])
    });

    setTimeout(() => this.form.patchValue({
      animal: 'cat'
      school : {name: 'Fraser'},
      students: ['Bob gets edited', 'This will not show']
    }), 250);

}

只会更新"students"中的第一个元素,但不会插入第二个元素。

我需要做什么才能同时显示两个元素?

这里是Plunker链接

4个回答

21

好的,就像silentsod所说,这是不可能的。目前,我正在使用以下内容作为替代方案:

        let controlArray = <FormArray>this.form.controls['apps'];           
        this.list.forEach(app => {
                    const fb = this.buildGroup();
                    fb.patchValue(app);
                    controlArray.push(fb);
            });

Angular团队 - 我们需要一个类似PatchArray()的新函数,可以从集合/对象图中进行修补。这是一个基本的使用案例。


17

.patchValue() 方法只会更新现有的 FormArray,而不会修改表单模型的结构。

patchValue(value: any[], {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}): void

对 FormArray 的值进行修补。它接受一个与控件结构匹配的数组,并将尽力将值匹配到组中的正确控件。

它可以接受超集和子集数组而不会抛出错误。

如果要使新元素出现,您实际上需要将其推入数组中。

 this.form.controls['students'].push(new FormControl('This will not show'));

这一切都在 FormArray 文档中。 https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html


6
如何事先知道需要推送多少表单控件? - kostia
好问题 @kostia。你能想出来吗? - Max

7

好的,我找到的解决方案是:

this.myForm.controls['array'] = this.formBuilder.array(newArray.map(i => this.formBuilder.group(i)));

如何在Angular 4中通过ngFor迭代值时创建动态的FormControlName。 - User 123

0

希望这能对你有所帮助。我的对象非常复杂,其中包含一个内部对象和内部对象中的对象。抱歉我的语法不好,但我希望我的代码能够帮到你。

ngOnInit() {
    this.descriptifForm = this._fb.group({
      name: 'ad',
      descriptifs: this._fb.array([ this.buildForm() ]),
    });

    this._service.getData().subscribe(res => {
      this.descriptifForm.setControl('descriptifs', this._fb.array(res || []));
    });

  }
buildA(): FormGroup {
    return this._fb.group({
      Id: '',
      Groups: this._fb.array([ this.buildB() ]),
      Title: ''
    });
  }

  buildB(): FormGroup {
    return this._fb.group({
      Id: '',
      Fields: this._fb.array([ this.bbuildC() ]),
      Type: ''
    });
  }

  buildC(): FormGroup {
    return this._fb.group({
      Answers: this._fb.array([ this.buildD() ]),
      Code: '',
    });
  }

  buildD(): FormGroup {
    return this._fb.group({
      Data: ''
    });
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接