以反应形式

时间:2018-02-19 12:59:07

标签: javascript angular typescript

我的应用中有Reactive Form,结构如下:

this.bioForm = this._fb.group({
  firstName: [this.user.firstName, [Validators.required]],

  experience: this._fb.group({
    field0: ['', [Validators.required, Validators.maxLength(500)]],
    field1: ['', [Validators.required, Validators.maxLength(500)]],
    field2: ['', [Validators.required, Validators.maxLength(500)]],
    field3: ['', [Validators.required, Validators.maxLength(500)]],
    field4: ['', [Validators.maxLength(500)]],
    field5: ['', [Validators.maxLength(500)]]
  }),

  skills: this._fb.array([], Validators.required),
});

在我的浏览器local storage中,我有以下内容:

enter image description here

我尝试了什么:

 // Get Value from LOCAL STORAGE
 let localStorage_experience = JSON.parse(localStorage.getItem("experience")) || "";

 // Set nested form controls value
 this.bioForm.setValue({experience:{field0: localStorage_experience.field0 || ""}});

我正在尝试从我的本地存储中检索值,并根据我的嵌套表单控件值设置它们。

1 个答案:

答案 0 :(得分:3)

您可以使用setControl替换现有的formcontrol / formgroup / formarray:

this.bioForm.setControl('experience', this._fb.group(localStorage_experience));

<强> StackBlitz

或者您可以使用patchValue

this.bioForm.patchValue({experience: localStorage_experience}); 

如果您想使用setValue,则需要将其应用于嵌套表单组,因为setValue期望设置所有值。

this.bioForm.controls.experience.setValue(localStorage_experience);