@Random Guy,将数据从 json 传递到 FormBuilder 的关键是使用数组的“map”方法。但首先,请使用 HttpClient 而不是旧的和不推荐使用的 http (所以,你不需要使用这个丑陋的地图((response:Response)=> response.json())}
好吧,你在构造函数中导入 formBuilder
constructor (private fb:FormBuilder){}
并创建一个函数,接收您的 json 或 null 作为参数并返回 fromGroup
createForm(data: any): FormGroup {
return this.fb.group({
//id data.companies, we create a formArray
companies: data ? this.fb.array(this.createGroupProjects(data.companies)) : []
})
}
//return an array of FormGroups
createGroupProjects(companies: any[]): FormGroup[] {
//with each element in companies
return companies.map(c => {
//create a formGroup
return this.fb.group({
company: c.company,
//projects will be a form array too
projects: this.fb.array(this.createProjects(c.projects))
})
})
}
//return an array of FormGroups
createProjects(projects: any[]): FormGroup[] {
//with each project
return projects.map(p => {
//return a FormGroup
return this.fb.group({
projectName: p.projectName
})
})
}
当然你可以只使用一个函数
createForm(data: any): FormGroup {
return this.fb.group({
//in "companies" if data.companies, we return a FormArray
//with each element of data.companies we return a formGroup
companies: data ? this.fb.array(data.companies.map(c => {
return this.fb.group({
company: c.company,
//the propertie projects will be another FormArray
//with each element in projects
projects: this.fb.array(c.projects.map(p => {
//return a formGroup
return this.fb.group({
projectName: p.projectName
})
}))
})
}))
//If data=null, you return an array
: []
})
}
看到你的 FormArray 是使用 this.bt.array(...a formGroup array...) 创建的,而这个 formGroupArray 是使用“map”创建的。