0

I have an object of values in angular and I want to add that object to my formGroup. But somehow I am unable to do that. Please check my code and let me know where I am wrong.

 ngOnInit() {
    this.socialMediaForm = this.fb.group({
      //---------------------//
      //   Add values here  //
      //-------------------//
      socialAccounts: this.fb.array([]),
    });

    const userInfo = JSON.parse(localStorage.getItem('user_info'));

    for (const [key, value] of Object.entries(userInfo)) {
      this.socialMediaForm.patchValue({ [key]: value });
    }
  }

Any solution appreciated!

2 Answers 2

3

you need add the FormControls to your form. For this, you need use the method addControl

for (const [key, value] of Object.entries(userInfo)) {
    const control=this.socialMediaForm.get(key)
    if (!control) //if not has a control called "key"
        this.socialMediaForm.addControl(key,new FormControl(value))
    else
        control.setValue(value);
}

If you're sure that has no control you can simply

for (const [key, value] of Object.entries(userInfo)) {
    this.socialMediaForm.addControl(key,new FormControl(value))
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to add values from an object to a form then you need to create another nested FormGroup variable inside your main FormGroup.

 ngOnInit() {
    this.socialMediaForm = this.fb.group({
      userInfo : this.fb.group({}),
      socialAccounts: this.fb.array([]),
    });

    const userInfoFromStorage = JSON.parse(localStorage.getItem('user_info'));

    this.socialMediaForm.patchValue({userInfo:userInfoFromStorage});

  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.