更改嵌套表单中的 FormBuilder 数组项

2023-12-13

根据 API 文档,更改嵌套值的正确方法是使用方法patchValue

myForm.patchValue({'key': {'subKey': 'newValue'}});

但是如何更改嵌套数组中的值,例如list下面这个例子中的汽车数量。如何获得第一项list排列一个变化model to Fiesta? Plunker

myForm.patchValue({'list': 0: {'model': 'Fiesta'});不管用。

@Component({
  moduleId: __moduleName,
  selector: 'my-app',
  template: `<div><pre>{{ myForm.value | json }}</pre></div>`
})
export class AppComponent {

  public myForm: FormGroup;

  constructor(@Inject(FormBuilder) private _fb: FormBuilder) {

    this.myForm = this._fb.group({
      name: 'Cars',
      list:  this._fb.array([
        this.initCar(),
        this.initCar(),
        this.initCar()
      ]),
    });
    /** Change value Here **/
    this.myForm.patchValue({name: 'Automobile'});
  };

  initCar() {
    return this._fb.group({
      automaker: 'Ford',
      model:     'Fusion'
    });
  }
}

Plunker


不久前我做了类似的事情,只是补充一下。

const patchV = (<FormArray>this.myForm.controls['list']).at(0) as FormArray;
patchV.patchValue({automaker: 'CoolCar', model: 'Bucket'})

工作示例 [plunker]http://embed.plnkr.co/VWicnA/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更改嵌套表单中的 FormBuilder 数组项 的相关文章

随机推荐