如何在Angular 6中使用动态创建的字段创建和绑定动态模型

时间:2018-08-31 06:36:19

标签: html json angular typescript angular6

我有一个任务,我需要点击Get API,并且在该API响应中,我得到HTML字段的键(API键可以是2个或更多),我需要根据该键动态创建HTML表单。 以下是我创建表单的HTML代码:

<form class="form-horizontal" #f1=ngForm>
  <div class="clearfix"></div>
  <div class="row">
    <div class="col-12">
      <div class="form-row" *ngFor="let aux of AuxfieldAndData">
        <div class="form-group col-md-6">
          <label for="Credit Limit Currency"> {{aux.ColumnTitle}}</label>
          <select class="form-control" *ngIf="aux.DropDownArray.length !== 0; else txtBox" [(ngModel)]="aux.ColumnName" [name]="aux.ColumnName">
            <option [value]="field.key" *ngFor="let field of aux.DropDownArray">{{field.value}}</option>
          </select>
          <ng-template #txtBox>
            <input type="text" class="form-control" [(ngModel)]="aux.ColumnName" [name]="aux.ColumnName">
          </ng-template>
        </div>
      </div>
    </div>
    <div class="col-md-12 text-right mt-3">
      <button type="submit" id="submit" (click)=" doOnSubmit($event)" class="btn btn-primary">
        <i class="fa fa-floppy-o"></i> Save
      </button>
    </div>
  </div>
</form>

和读取用TypeScript编写的API数据的方法:

createDynamicFields(dataArray: Array<any>) {
    dataArray.forEach(auxiliary => {
      const dropValue = auxiliary.values;
      const dropdownList = [];
      if (dropValue !== null) {
        const DVal = Object.keys(auxiliary.values);
        DVal.forEach(DropDownVal => {
          const list = {
            key: DropDownVal,
            value: dropValue[DropDownVal]
          };
          dropdownList.push(list);
        });
      }
      const array = {
        ColumnTitle: auxiliary.columnTitle,
        DropDownArray: dropdownList,
        ColumnName: auxiliary.columnName
      };
      this.AuxfieldAndData.push(array);
    });
  }

我在这里成功创建了表单,但是我不知道如何创建其模型并将其与表单绑定以发布表单数据 我也在下面分享了API响应:

{
   "auxiliaryformfeild":[
      {
         "columnName":"credit_currency",
         "columnTitle":"Credit Limit Currency",
         "values":{
            "Euro":"EUR",
            "Sterling":"GBP",
            "US Dollar":"USD"
         }
      },
      {
         "columnName":"credit_limit",
         "columnTitle":"Credit Limit",
         "values":null
      }
   ],
   "Status":"OK"
}

请在上述情况下帮助我。预先感谢。

0 个答案:

没有答案