Angular2 patchValue 将值推入数组

Angular2 patchValue push value into array

是吗 看起来 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 here.

.patchValue() 仅更新现有的 FormArray,不会修改您的表单模型的结构。

patchValue(value: any[], {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Patches the value of the FormArray. It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group.

It accepts both super-sets and sub-sets of the array without throwing an error.

您实际上需要将新元素推送到数组中才能显示它。

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

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

好吧,正如silentsod所说的那样,这是不可能的。目前,我正在使用以下替代方法:

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

Angular 团队 - 我们需要一个类似于 PatchArray() 的新函数,它可以从 collection/object 图进行修补。这是一个基本用例。

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

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

希望对您有所帮助。我有一个复杂的对象,其中我的对象内部有一个对象,内部有一个对象。对不起我的语法。但我希望我的代码能帮到你

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