首页 > 解决方案 > 迭代反应式表单控件

问题描述

基本上我想将所有反应形式的值保存在会话存储中,刷新时我想从会话存储中获取值以显示在表单中。

所以我想做的是迭代反应式表单控件,并从这些值构造一个对象

该对象可以设置为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;
    }
  }

标签: angularangular-reactive-forms

解决方案


使用this.profileForm.valuewhich 会给你一个对象:

{
    firstname: "john" 
    phoneNo: "12344567"
    selectedService : [
        true,
        false,
        true
    ]
    gender : "male"
}

您会注意到它selectedService不包含服务名称,但它们将按顺序排列,在迭代数组时应该可以正常工作。


推荐阅读