Skywalker
Skywalker

Reputation: 5194

Set nested form group/control values in reactive forms

I have a Reactive Form in my app and the structure is below:

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),
});

Within my browser local storage I have the following:

enter image description here

What I have tried:

 // 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 || ""}});

I am trying to retrieve value from my local storage and set them against my nested form controls values.

Upvotes: 1

Views: 3910

Answers (1)

AVJT82
AVJT82

Reputation: 73337

You could use setControl that replaces an existing formcontrol/formgroup/formarray:

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

StackBlitz

or then you can use patchValue:

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

If you want to use setValue you need to apply it on the nested formgroup, as setValue expects all values to be set.

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

Upvotes: 7

Related Questions