从嵌套类设计嵌套的反应形式 [英] Designing nested reactive forms from nested classes

查看:83
本文介绍了从嵌套类设计嵌套的反应形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

class License {
   name:string;
   .. lots of other fields.
   nameAttributes:NameAttributes[];
}

class nameAttributes:NameAttributes{
   index:number;
   attribute:string;
}

我知道我可以像这样创建表单,但是它要求我手动创建每个字段(控件),并且每次许可证类更改时,我都必须使用新字段来更新类和这个formGroup.

I know I can created the form like this, but it requires that I manually create each field(control) and every time the licences class changes, I have to update the class and this formGroup with the new fields.

       this.licenseForm = formBuilder.group({
          name:['name value'],
          otherFields:['their values'],
          nameAttributes: this.formBuilder.array([
            this.formBuilder.group({
              index:[1],
              attribute:["attr1"]
            }),
            this.formBuilder.group({
              index:[2],
              attribute:["attr2"]
            })
          ])
      });

我希望将许可证类传递到formBuilder中,它会自动创建必要的FormGroups并根据其名称使它们可用,因此下面将创建两个组,一个"license"组和一个嵌套的"nameAttributes"组,其中包含所有与license和nameAttributes相关的控件.

I would prefer if I could just pass the license class into formBuilder and it would create the necessary FormGroups automatically and make them available based on their name, so the following would create two groups, a "license" group and a nested "nameAttributes" group with all of the associated controls for license and nameAttributes.

      this.licenseForm = formBuilder.group({
        license:formBuilder.group(license)
      });

我丢失了某些东西吗?或者没有一些严肃的自省代码,这是不可能的吗?

Am I missing something or is this just not possible without some serious class introspection code?

推荐答案

如果您的对象有数据,您当然可以做到

If your object has data, of course you can do it

看看这个 stackblitz

您具有类似

  createForm(data:any):FormGroup
  {
    const group=new FormGroup({});
    for (let key in data)
    {
      if (Array.isArray(data[key])) //if is an array
      {                             //first create the formArray
        group.addControl(key,new FormArray([this.createForm(data[key][0])]))
        for (let i=1;i<data[key].length;i++)  //after add the rest of the elements
          (group.get(key) as FormArray).push(this.createForm(data[key][i]))
      }
      else
      {
        if (typeof(data[key])=="object") //if is an object we add a formGroup
          group.addControl(key,this.createForm(data[key]))
        else  //add a simple control
          group.addControl(key,new FormControl(data[key]))
      }
    }
    return group
  }

并命名为

this.form=this.createForm(this.obj)

这篇关于从嵌套类设计嵌套的反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆