将JSON数据绑定到反应形式

时间:2018-09-23 09:24:23

标签: angular angular-reactive-forms angular-formbuilder

我遇到了以下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())}

和Organization类如下:

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

我在组件文件的Organization类的对象中具有上述JSON数据,并且我想在html文件的表单字段中呈现此数据。我尝试使用ngModel绑定数据,但在无法以模型驱动形式使用ngModel的地方读取了它。我该如何实现?

1 个答案:

答案 0 :(得分:0)

@Random Guy,将数据从json传递到FormBuilder的关键是使用数组的“ map”方法。但是首先,请使用HttpClient而不是旧的和已弃用的http(因此,您不必使用此丑陋的map((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(... formGroupArray ...)创建的,而此formGroupArray是使用“ map”创建的。