代码之家  ›  专栏  ›  技术社区  ›  Skywalker

在反应式窗体中设置嵌套窗体组/控件值

  •  1
  • Skywalker  · 技术社区  · 7 年前

    我有一个 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 回复  |  直到 7 年前
        1
  •  7
  •   AT82    7 年前

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

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

    StackBlitz

    或者你可以使用 patchValue :

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

    如果要使用 setValue 您需要将其应用于嵌套的formgroup,如下所示 设置值 期望 全部的 要设置的值。

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