1

I have this reactive form in the Ionic3 framework, which I need to populate with data I retrieve from API. To do so I am using patchValue as I read somewhere that it is more reliable than setValue.

The problem I am facing is, it does not populate repeated form fields. To explain better I've created this example code.

I have tried other ways around like directly assigning data to the respective field instead of using for loop first, but that only populated 1 set instead of all 3.

Can someone point out what I am doing wrong, or provide a better solution?

Thank you

3
  • Your code works fine. It's just that your populate method creates new FormGroups and populates them with patchValue(), but never pushes these new form groups to the form array. Commented Oct 26, 2018 at 18:40
  • 1
    patchValue() is not "more reliable". It does something different than setValue(). setValue expects a complete new value (containing a new value for every control of the form), whereas patchValue expects a partial new value (containing a new value for some of the controls of the form). Commented Oct 26, 2018 at 18:43
  • Thank you @JBNizet Commented Oct 26, 2018 at 19:19

1 Answer 1

1

In your example set your for loop on the home component to look like this

for(const rooms of resp.room_data){

      const roomNumberControl = this.createRooms();
      (<FormArray>this.informationForm.controls.room_numbers).push
      (roomNumberControl);
      console.log(JSON.stringify(rooms));
    }

Create rooms would just need to have some data in them but that will create on object for everyone in the array. This is how I have done it in the past.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, that worked like charm, but it leaves the first field empty. Can you tell me how can I fix this? stackblitz.com/edit/ionic-c5vapg
remove this.createRooms() from line 17 when the form is initialized you are populating it with a vaule
So silly of me, thank you so much again. You saved my day

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.