0

我遇到了以下 Stackblitz 演示:

https://stackblitz.com/edit/angular-dffny7?file=app

参考以下帖子:https ://stackoverflow.com/a/48527939/7429196

现在假设我有以下 JSON

{
 "companies": [
  {
   "company": "ABC",
   "projects": [
     {
     "projectName": "DEF"
     },
     {
     "projectName": "GHI"
     }
    ]
   },
   {
    "company": "JKL",
    "projects": [
     {
     "projectName": "MNO"
     }
   ]
  }
 ]
}

来自以下服务:

getCompanies() : Observable<Organization>{
return this.http.get(url).map((response: Response)=> response.json())}

组织类如下:

export class Organization{
public company: String;
public projects : Project[];
}
export class Project{
public projectName : String;
}

我的组件文件中的组织类对象中有上述 JSON 数据,我想在 html 文件的表单字段中呈现这些数据。我尝试使用 ngModel 绑定数据,但在某处读到 ngModel 不能在模型驱动形式中使用。我怎样才能实现它?

4

1 回答 1

1

@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”创建的。

于 2018-09-23T13:22:21.813 回答