Angular2 patchValue 将值推入数组 [英] Angular2 patchValue push value into array
问题描述
它看起来像Angular2的FormGroup.patchValue() 不会将新元素推入数组.
Is it It looks like Angular2's FormGroup.patchValue() doesn't push new elements into an array.
例如像这样:
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"中的第一个元素,但不会插入第二个元素.
Will only update the first element in "students" but it will not insert the second element.
我需要怎么做才能显示这两个元素?
What would I need to do to make it display both elements?
推荐答案
.patchValue()
只更新现有的 FormArray
,不会修改你的结构表单模型.
.patchValue()
only updates the existing FormArray
, it won't modify the structure of your form model.
patchValue(value: any[], {onlySelf, emitEvent}?: {onlySelf?: boolean,emitEvent?: boolean}) : void 修补 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.
您实际上需要推送一个新元素到数组中,以便它出现.
You actually need to push a new element onto the array in order for it to appear.
this.form.controls['students'].push(new FormControl('This will not show'));
这都在 FormArray
文档中 https://angular.io/docs/ts/latest/api/forms/index/FormArray-class.html
这篇关于Angular2 patchValue 将值推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!