angular - 迭代反应式表单控件
问题描述
基本上我想将所有反应形式的值保存在会话存储中,刷新时我想从会话存储中获取值以显示在表单中。
所以我想做的是迭代反应式表单控件,并从这些值构造一个对象
该对象可以设置为this.form.patchValue(object);
我想遍历我的响应式表单中的每个表单控件并创建一个结构化对象。
例如 :
profileForm = new FormGroup({
firstName: new FormControl(''),
phoneNo: new FormControl(''),
selectedService : FormArray('')
gender:new FormControl(''),
});
在这种情况下selectedService
是从多个复选框派生的。然后我想创建一个这样的对象:
核心价值
{
firstname: "john"
phoneNo: "12344567"
selectedService : {
service1: true,
service2: false,
service3: true
}
gender : "male"
}
这是我尝试过的,但我未能为formArray
getFormFieldsValue(formControl: any): void {
Object.keys(formControl.controls).forEach((controlName) => {
const control = formControl.controls[controlName];
if (control.controls) {
this.getFormFieldsValue(control);
} else {
this.createObject(controlName, control);
}
});
}
createObject(controlName: any, controlValue: any): any {
if (controlValue.value) {
this.objects[controlName] = controlValue.value;
}
}
解决方案
使用this.profileForm.value
which 会给你一个对象:
{
firstname: "john"
phoneNo: "12344567"
selectedService : [
true,
false,
true
]
gender : "male"
}
您会注意到它selectedService
不包含服务名称,但它们将按顺序排列,在迭代数组时应该可以正常工作。
推荐阅读
- spring - 在嵌套的实体列表中按属性查找实体
- vba - 如何在 VBA 中显示用户窗体的图形编辑器视图(关闭后)?
- java - 在 configServer 中添加过滤器
- regex - 如何使用验证器验证 asp 页面以验证文本框以允许 2 种不同长度的输入?
- java - JFrame颜色变化
- ruby-on-rails - 从 Mounted Gems 运行 Rspecs
- angular - Angular - TypeError:无法读取未定义的属性“jobTitle”
- javascript - 使用 javascript 检测可变字体支持
- python - 为什么在 JsonResponse 中使用非字典对象不好?
- go - 与 goroutine 混淆