首页 文章

Angular2 patchValue将值推入数组

提问于
浏览
15

它看起来像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);

}

只有 update "students"中的第一个元素,但它不会 insert 第二个元素 .

我需要做什么才能让它显示两个元素?

Plunker here .

4 回答

  • 2

    .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

  • 0

    好吧,正如silentsod所说,这是不可能的 . 目前,我正在使用以下作为替代方案:

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

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

  • 14

    好吧,我发现的解决方案是:

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

    我希望这能帮到您 . 我有一个复杂的对象,我的对象里面有一个对象,里面有对象 . 对不起我的语法 . 但我希望我的代码可以帮到你

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

相关问题