3

I have a reactive form with multiple nested form arrays. In my form i can have multiple segments with multiple sets, the problem is using patchValue() or setValue() to edit my form, when getting data from the database. I understand i need to create multiple form groups to patch the values, is there a way of dynamically creating the form to match the data received from the database?

ngOnInit() {
      this.myForm = this.fb.group({ 
        id: '', 
       name: '',
       userId: "",
       description:'',
       date: "",

      segments: this.fb.array([
         this.fb.group({
           id:'',
           workoutId:'',
           name:'',
           notes: '',
           exerciseName:'',

       sets: this.fb.array([
             this.fb.group({
               id:'',
               segmentId:'',
               name:'',
               reps:'',
               weight:'',
               type:'',
               success:'',
             }),
        ])
     })
   ])
 });
    this.workoutService.getWorkout(this.workoutId).subscribe(
      (Workout) => { this.workout = Workout, this.setValueForm()},
      (err) => console.log(err, "This did not load properlu make a toasty"),
    ) 

}

setValueForm() {
  this.myForm.patchValue(this.workout);  

}

1 Answer 1

4

Try like this:

let segments = res.segments // value from db

const formArray = new FormArray([]);

segments.forEach(s => {
  formArray.push(this.fb.group({
    id: s.id,
    name: s.name
  }));
});


this.myForm.setControl('segments',formArray);
Sign up to request clarification or add additional context in comments.

1 Comment

Would the same techbe valid if a contorll contained a nested form Array l

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.