迭代反应式控件

时间:2019-01-04 10:43:45

标签: angular angular-reactive-forms

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

所以我想做的是遍历反应式表单控件,并根据这些值构造一个对象

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

2 个答案:

答案 0 :(得分:1)

使用this.profileForm.value将为您提供一个对象:

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

您会注意到selectedService不包含服务名称,但是它们将保持顺序,在遍历数组时应该可以正常工作。

答案 1 :(得分:0)

如果要存储并从会话存储中获取值,则应使用JSON.stringify(this.profofileForm.value)。因此,您将得到一个比可以存储的字符串。稍后,您可以使用JSON.parse取回对象。 要以表格形式加载值,可以在FromControl对象中将其初始化:

profileForm = new FormGroup({
    firstName: new FormControl('this.valFirstName'),
    phoneNo: new FormControl('this.valPhoneNo'),
    selectedService : FormArray('this.SelectedService')
    gender:new FormControl('this.gender'),
  });

其中valXxxxx值来自会话存储中已解析的json对象。

相关问题