html - 使用字典在 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}} </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"}],
}
我检查了answer和answer,它使用了FormArray
andFormGroup
但我无法使用我对 Angular 和 typescript 的有限知识来使用它。任何帮助,将不胜感激。
解决方案
注意:此答案如果要使用 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))
推荐阅读
- python - 可以在 Keras 中的 2D CNN 之后添加双向 LSTM 吗?
- java - Java 代码中的 InputMismatchException 错误。请给点建议
- algorithm - 时间复杂度的最低上限
- node.js - 即使在 promisify 之后也阻止传入的请求
- python - Discord bot 未按名称查找频道
- docker-compose - 如何访问 Azure App Service 应用程序日志以检查 Docker Compose 错误?
- firebase - Firebase 数据库未在颤振应用程序中更新
- algorithm - 归并排序的粗化
- html - 如何通过单击按钮从数组中加载选定的选项 JSON 对象?
- reactjs - 如何引用 React 组件的值