【发布时间】:2019-05-30 22:23:20
【问题描述】:
基本上我想将所有响应式表单值保存在会话存储中,刷新时我想从会话存储中获取值以显示在表单中。
所以我要做的是迭代反应式表单控件,并从这些值构造一个对象
该对象可以设置为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;
}
}
【问题讨论】:
-
您是否尝试过 console.log(this.profileform.value) 理想情况下,表单本身应该为您提供所需的对象作为其值,我们设计反应式表单以使其返回表单中的值的对象。例如 formGroup 返回对象,表单控件返回原语,formArray 返回 Array
-
@AkshayRajput - 请参阅下面的答案 cmets。
-
如果需要修改表单的一部分可以使用patch 如果需要修改完整的表单可以使用set
-
您尝试过使用
form.getRawValues()吗?这是获取给定 formGroup 中所有控件的所有值的一种非常有效的方法。
标签: angular angular-reactive-forms