使用formBuilder angular 2在formArray中动态创建formGroup [英] dynamic formGroup within formArray using formBuilder angular 2
问题描述
我的后端有一个名为media的数组,可以存储多个对象.看起来像这样:
I have an array on my backend called media that stores several objects. It looks something like this:
"media": [
{
"srcId": null;
"primary": false,
"thumbs": {
"default": null
},
"type": null,
"raw": null
}
]
将这个数组加载到表单中的我的edit-component.ts看起来像这样:
My edit-component.ts for the loading this array into the form looks like this:
media: this._fb.array([
this._fb.group({
srcId: new FormControl(this.existingMedia.srcId),
type: new FormControl(this.existingMedia.type),
raw: new FormControl(this.existingMedia.raw),
primary: new FormControl(this.existingMedia.primary),
thumbs: this._fb.group({
default: new FormControl(this.existingMedia.thumb.default)
})
})
]),
现在,这将从该媒体阵列中加载第一个对象,但不会加载该阵列中可能存在的其他媒体对象.有没有一种方法可以使formArray Media内部的formBuilder组动态调整到后端Media Array中的对象数量?
Right now this will load the first object from that media array but not other media objects that could be in the array. Is there a way to make the formBuilder group inside the formArray Media dynamic to the number of objects within the Media Array on the backend?
任何帮助/提示/建议将不胜感激!
Any help/tips/suggestions would be much appreciated!
更新
在我的ngOnInit中,我有:
In my ngOnInit I have:
this.currentCard = selectedCurrentCard;
for (let medias of this.currentCard.media){
this.existingMedia = medias;
遍历后端的媒体阵列,并
to iterate over my media array on the backend and
const control = <FormArray>this.cardForm.controls['media'];
control.push(this.initCurerntMedia());
具有initCurrentMedia()的样子:已更新initCurrentMedia(),此更新版本在ngOnInit()中调用时有效,这要归功于@ AJT_82
with initCurrentMedia() looking like this: UPDATED initCurrentMedia() this updated version worked when called in ngOnInit() Thanks to the help of @AJT_82
initCurrentMedia() {
this.currentCard.media.forEach(media => {
const control = <FormArray>this.cardForm.controls['media'];
control.push(
this._fb.group({
srcId: new FormControl(media.srcId),
type: new FormControl(media.type),
raw: new FormControl(media.raw),
primary: new FormControl(media.primary),
thumbs: this._fb.group({
default: new FormControl()
})
})
)
})
}
使用当前媒体填充我的表单.它仍然只填充一个对象.
To populate my form with current media. It is still only populating one object.
推荐答案
我喜欢构建表单
this.myForm = this._fb.group({
media: this._fb.array([])
})
,然后在获取响应后设置值,因此在获取响应后,您可以调用方法,例如 setForm()
:
and then after response have been fetched set the values, so after getting the response you can call a method, let's say setForm()
:
setForm() {
this.media.forEach(x => {
this.myForm.controls.media.push(
this._fb.group({
srcId: x.srcId,
type: x.type,
raw: x.raw,
primary: x.primary,
thumbs: this._fb.group({
default: x.thumbs.default
})
)
})
})
}
这篇关于使用formBuilder angular 2在formArray中动态创建formGroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!