首页 > 解决方案 > 具有多个步骤和嵌套字段的角度形式

问题描述

我被分配到使用正式构建表单的项目。它们中的大多数要么是普通的单页表单,要么是 jsonSchema 之外的表单。我被要求研究带有标签等的嵌套表单。

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: {
   ...
   }
}

标签: jsonangulartypescriptangular-reactive-formsangular-formly

解决方案


您需要使用 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]
    })
}

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


推荐阅读