【问题标题】:How create dynamic form controls and fetch data from it in Angular如何在 Angular 中创建动态表单控件并从中获取数据
【发布时间】:2021-03-21 12:46:03
【问题描述】:

我对 Angular 很陌生,遇到了一个问题。

当组件加载时,我有两个输入字段作为终端 ID(文本字段)和终端类型(下拉)。从下拉列表中选择值后,onChange 方法会进行 API 调用并为我获取数据。数据格式如下:

    data={
   "productResults":[
      {
         "productId":"1",
         "productName":"credit"
      },
      {
         "productId":"2",
         "productName":"debit"
      }
   ],
   "metaResultList":[
      {
         "customizationType":"time",
         "customizationValue":"0420",
         "longDescription":"Item1"
      },
      {
         "customizationType":"code",
         "customizationValue":"N",
         "longDescription":"Auto Close",
         "customizationCodeDetail":{
            "customizationCodeDetails":[
               {
                  "value":"N",
                  "shortDescription":"None"
               },
               {
                  "value":"H",
                  "shortDescription":"host Auto Close"
               }
            ]
         }
      },
      {
         "customizationType":"bool",
         "customizationValue":"Y",
         "longDescription":"Block Account"
      },
      {
         "customizationType":"bool",
         "customizationValue":"N",
         "longDescription":"Block Sales"
      },
      {
         "customizationType":"number",
         "customizationValue":"55421",
         "longDescrption":"Max Value"
      }
   ]
}

我所做的是当我从下拉列表中选择后获取数据时,我在这两个文件下面有两个部分,它们将显示为 ngIf I get data:

第一个:产品部分 - 我使用 ngFor 像这样迭代 data.productResults 并显示切换

<div *ngFor="let product of data.productResultResults">
    <label>{{product.productName}}</label>
    <ion-toggle></ion-toggle>

</div>

第 2 部分:其他部分:这里我遍历 metaResultList 以显示文本字段,如果自定义类型是时间或数字,如果自定义类型是代码,则下拉,如果自定义类型是布尔,则切换。

<div *ngFor="let other of data.metaResultList">
    <div *ngIf="other.customizationType==='time'||other.customizationType==='number'">
<label>{{other.longDescription}}</label>
<input type="text" value="other.customizationValue"/>
    </div>
     <div *ngIf="other.customizationType==='bool'">
<label>{{other.longDescription}}</label>
<ion-toggle></ion-toggle>
    </div>
    <div *ngIf="other.customizationType==='code'">
<label>{{other.longDescription}}</label>
<dropdown [datalist]="autoCloseDropDown"></dropdown>
    </div>
    </div>

此下拉列表是我的自定义下拉列表,我将值传递为 H 代表主机自动关闭,N 代表无,我在下拉列表中获得选项(我在获得结果后执行了该逻辑)。

点击下面的提交按钮后,我希望我的数据采用这种格式

{
   "tid":"3",
   "terminalType":"gateway",
   "products":[
      {
         "productId":"1",
         "productname":"credit"
      }
   ],
   "customizations":[
      {
         "customizationName":"Item1",
         "customizationValue":"0420"
      },
      {
         "customizationName":"Block Account",
         "customizationValue":"Y"
      },
      {
         "customizationName":"Block Sales",
         "customizationValue":"N"
      },
      {
         "customizationName":"Max Value",
         "customizationValue":"54556"
      }
   ]
}

现在我的问题是如何制作表单控件,因为这些字段是在我在终端类型下拉列表中做出决定后生成的,但我已经在 ngOnInit 中制作了表单组。我应该如何使表单控件名称动态化。我将如何仅在 products 数组中插入那些值为 Y 形式的值。在下拉列表中进行更改后,我有什么方法可以实例化表单组吗?另外,有时我可能不会从 api 获得某些字段,例如 type=bool,所以我不会在 FrontEnd 中显示它

任何帮助将不胜感激。

【问题讨论】:

    标签: json angular typescript


    【解决方案1】:

    如果你想通过一个对象或者一个数组来生成动态的formControl,可以使用下面这个方法:

    public builder(data: any): FormGroup | FormArray {
      if (Array.isArray(data)) {
        const formGroup = [];
        for (const d of data) {
          formGroup.push(this.builder(d));
        }
        return this.formBuilder.array(formGroup);
      } else {
        const formGroup = {};
        Object.keys(data).forEach((key) => {
          if (typeof data[key] === 'object' && data[key] && !Array.isArray(data[key])) {
            Object.assign(formGroup, {
              [key]: this.builder(data[key]),
            });
          } else if (Array.isArray(data[key])) {
            Object.assign(formGroup, {
              [key]: this.formBuilder.array([]),
            });
    
            data[key].forEach((newData: any) => {
              formGroup[key].push(this.builder(newData));
            });
          } else {
            Object.assign(formGroup, { [key]: [data[key]] });
          }
        });
        return this.formBuilder.group(formGroup);
      }
    }
    

    现在,如果你想生成一个对象或数组动态,你可以用参数数据作为对象或数组调用那个方法。举个例子:

    ngOnInit(): void {
    
      // will be generate a form array  generatedForm in formGroup
      const dynamicArray = [{ id: 1, name: 'John Doe'}, { id: 2, name: 'Jane Doe'}];
      this.formGroup = this.formBuilder.group({
        generatedForm: this.builder(dynamicArray)
      });
    
      // look at the form array
      console.log(this.formGroup.get('generatedForm'));
    
    
      // will be generated a formGroup by an object
      const dynamicObject = { id: 1, name: 'John Doe'};
      this.formGroup = <FormGroup>this.builder(dynamicObject)
    
      // dynamic formGroup by an object
      console.log(this.formGroup);
    }
    
    

    例如:您可以查看:https://stackblitz.com/edit/angular-ivy-7fm4d1

    好的,现在你可以用那个 builder 自己试试了。

    【讨论】:

      猜你喜欢
      • 2016-05-29
      • 1970-01-01
      • 2018-01-17
      • 1970-01-01
      • 2017-11-30
      • 2021-12-20
      • 2019-05-19
      • 2013-06-28
      • 1970-01-01
      相关资源
      最近更新 更多