问题描述
我正在尝试使用反应式表单循环遍历Angular中的嵌套表单控件。 有一个“ taskSchedule”,其中包含许多需要循环通过的“ note” API数据。
this.profileForm = new FormGroup({
userName: new FormControl(this.currentUserData.id),title: new FormControl(this.taskScheduleData.title),startDate: new FormControl(this.startDateConvert),endDate: new FormControl(this.endDateConvert),// this is where it should loop through the notes nested api data but it does not
this.taskScheduleData.forEach(element => {
this.notesForm = new FormGroup({
notesInfo: new FormControl(this.taskScheduleData.notes[element].notesInfo),});
});
});
API数据
{
"id": 10,"title": "Post test with notes","start": "2020-09-14T12:00:00","end": "2020-09-14T17:30:00","userId": 2,"notes": [
{
"id": 4,"notesInfo": "This is third notes","dateCreated": "2020-09-14T12:12:00","taskScheduleId": 10
},{
"id": 6,"notesInfo": "this is second notes","dateCreated": "2020-09-20T22:43:00","userId": 3,{
"id": 7,"notesInfo": "this is third notes","taskScheduleId": 10
}
]
}
阴影名称:“ element”(无阴影变量)
很显然,我编写的foreach循环不正确。有没有办法遍历3个嵌套的“ notes” API数据,以便每个note元素都有自己的控件形式?
解决方法
我认为您正在寻找FormArray,而不是formGroup。如果只想管理notesInfo,则可以创建FormControls的formArray
getFormGroup(data:any=null)
{
data=data || {userName:null,title:null,startDate:null,endDate:null,notes:null}
return new FormGroup({
userName: new FormControl(data.userName),title: new FormControl(data.title),startDate: new FormControl(data.start?new Date(data.start):null),endDate: new FormControl(data.endDate?new Date(data.endDate):null),notes:new FormArray(data.notes?
data.notes.map(x=>new FormControl(x.notesInfo):
[]
)
})
}
如果要管理notesInfo和注释,则可以创建FormGroups的formArray
getFormGroup(data:any=null)
{
data=data || {userName:null,notes:new FormArray(data.notes?
data.notes.map(x=>this.getGroupNotes(x)):
[])
})
}
getGroupNotes(data:any=null)
{
data=data || {id:nul,notesInfo:null,dateCreated:null,userId:null,taskSheduleId:null}
return new FormGroup({
id: new FormControl(data.id),notesInfo: new FormControl(data.notesInfo),dateCreated: new FormControl(data.dateCreated?new Date(data.dateCreated):null),userId: new FormControl(data.userId)
taskScheduleId: new FormControl(data.taskScheduleId)
})
}
然后您可以用作
this.profileForm=this.getFromGroup(data) // create a FormGroup with data
//or
this.profileForm=this.getFromGroup() // create a FormGroup empty