更改嵌套表单中的 FormBuilder 数组项 [英] Change FormBuilder array items in nested forms
问题描述
根据 API 文档,更改嵌套值的正确方法是使用方法 patchValue
myForm.patchValue({'key': {'subKey': 'newValue'}});
但是如何更改嵌套数组中的值,例如下面这个示例中的 list 汽车.如何获取 list 数组的第一项将 model
更改为 Fiesta
?Plunker
myForm.patchValue({'list': 0: {'model': 'Fiesta'});
不起作用.
@Component({模块 ID:__moduleName,选择器:'我的应用',模板:`{{ myForm.value |json }}</pre></div>`})导出类 AppComponent {公共 myForm:FormGroup;构造函数(@Inject(FormBuilder)私有_fb:FormBuilder){this.myForm = this._fb.group({name: '汽车',列表:this._fb.array([this.initCar(),this.initCar(),this.initCar()]),});/** 在此处更改值 **/this.myForm.patchValue({name: '汽车'});};initCar() {返回 this._fb.group({汽车制造商:福特",型号:'融合'});}}
解决方案 不久前我做了类似的事情,只是添加.
const patchV = (this.myForm.controls['list']).at(0) as FormArray;patchV.patchValue({汽车制造商:'CoolCar',型号:'Bucket'})
工作示例 [plunker]http://embed.plnkr.co/VWicnA/
According to the API documentation the proper way to change nested values is to use method patchValue
myForm.patchValue({'key': {'subKey': 'newValue'}});
But how to change values in nested arrays like list of cars in this example below. How to get first item of list array an change model
to Fiesta
? Plunker
myForm.patchValue({'list': 0: {'model': 'Fiesta'});
is not working.
@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'
});
}
}
解决方案 I did something similar not that long ago just add.
const patchV = (<FormArray>this.myForm.controls['list']).at(0) as FormArray;
patchV.patchValue({automaker: 'CoolCar', model: 'Bucket'})
Working Example [plunker]http://embed.plnkr.co/VWicnA/
这篇关于更改嵌套表单中的 FormBuilder 数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文