网站搜索

json - 带有多个步骤和嵌套字段的 Angular Formly 表单


我被分配到一个使用 Formly 构建表单的项目。大多数表单要么是简单的单页表单,要么是基于 JSON Schema 的表单。我被要求研究带有标签页等的嵌套表单。

https://stackblitz.com/edit/angular-ngx-formly-ouzzaa?file=app%2Fapp.component.html

它似乎可以正常工作,只是没有在模型中创建嵌套对象。我需要得到类似这样的东西:

{
   category1: {
      subcat1: {
         field1: 'value',
         field2: 'value'
      },
      subcat2: {
         field1: 'value',
         field2: 'value'
      }
   },
   category2: {
   ...
   }
}

答案#1

您需要按如下方式添加带有 FormArray 的 FormGroup...

  this.FormGroupName = fb.group({
    id: [null],
    //default form controls put here
    CatgoryList1: this.fb.group({
        List1: this.fb.array([
          this.fb.group({
            Field1: [null], //you can apply validation here
            Field2: [null]
          })
        ]),
        //and so on..
    }),
    CatgoryList2: this.fb.group({
        List2: this.fb.array([
          this.fb.group({
            Field3: [null],
            Field4: [null]
          })
        ]),
        //and so on..
    }),
    //and so on..
});  

你也可以像下面这样动态地推入表单...

this.CatList.push(this.initCatListGroup_Cat1());


get CatList() {
    return this.FormGroupName.get('CatgoryList1').get('List1') as FormArray;
}

initCatListGroup_Cat1() {
    return this.fb.group({
      Field1: [null],
      Field2: [null]
    })
}

我希望这对你有帮助。:)