首页 > 解决方案 > 使用字典在 Reactive 中添加动态字段并将它们推送到现有的 FormControl

问题描述

我正在尝试将一些字段动态加载到我的反应表单中。这是我拥有的字段(请注意,这些字段会根据选择而变化,因此我无法对其进行硬编码):

fields = [{  df_id: 48,
              df_name: "Phone Number",
              df_type: "text",
              df_options: "None",
              df_default: "None"
              },
              {
              df_id: 49,
              df_name: "Evaluering",
              df_type: "dropdown",
              df_options: ["Option1","Option2","Option3"],
              df_default: "None",
              }];

这是我在打字稿中尝试的内容:

this.testForm = this.formBuilder.group({
      start_date: ['', Validators.required],
      end_date: ['', Validators.required],
      call_direction: ['', Validators.required],
      items: this.formBuilder.array([])
    })


this.fields.forEach((x:any) => {
            this.testForm.addControl(x.df_name, new FormControl('',Validators.required));
          });

HTML文件如下所示:

<div class="row pt-2" *ngFor="let field of fields">
   <div class="col-4 d-flex align-items-center 13required">{{field.df_name}}&nbsp;  </div>
   <div class="col-6">
      <mat-form-field *ngIf="field.df_type == 'text'"  appearance="outline">
         <input matInput [type]="field.df_type" [formControlName]="field.df_name"  required/>
      </mat-form-field>
      <mat-form-field *ngIf="field.df_type == 'dropdown'"  appearance="outline">
         <mat-select [formControlName]="field.df_name" placeholder="">
            <mat-option
            [value]="option"
            *ngFor="let option of field.df_options"
            >
            {{ option }}
            </mat-option>
         </mat-select>
      </mat-form-field>
   </div>
</div>

这行得通!但是,表单值的格式不符合我的喜好,例如,

目前它看起来像:

{
"start_date":"2021-08-01",
 "end_date" : "2021-08-31",
 "call_direction": "Both",
 "items": [],
 "Phone Number": "3174",
 "Evaluering": "Option1"
}

我想要的是将它们推入items

{
"start_date":"2021-08-01",
 "end_date" : "2021-08-31",
 "call_direction": "Both",
 "items": [{"Phone Number": "3174", "Evaluering": "Option1"}],
}

我检查了answeranswer,它使用了FormArrayandFormGroup但我无法使用我对 Angular 和 typescript 的有限知识来使用它。任何帮助,将不胜感激。

标签: htmlangulartypescript

解决方案


注意:此答案如果要使用 FormGroup 创建 formArray,则应更改 .html 以管理 FormArray

您在哪里添加 FormControls?

像往常一样使用 FormArray,声明 formArray 的 getter

get itemsArray(){
   return this.fields.get('items') as FormArray;
}

我想拥有一个返回 FormGroup 的函数是件好事

createGroup(fields:any[]){
    //create a FormGroup Empty
    const group=new FormGroup({});

    //add the FormControl to the group
    fields.forEach((x:any) => {
            group.addControl(x.df_name, new FormControl('',Validators.required));
          });
     return group;
}

所以你可以使用

this.testForm = this.formBuilder.group({
      start_date: ['', Validators.required],
      end_date: ['', Validators.required],
      call_direction: ['', Validators.required],
      items: this.formBuilder.array([this.createGroup(this.fields)])
    })

//or to adding a new FormGroup to the array
this.itemsArray.push(this.createGroup(this.fields))

推荐阅读