3
votes

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

1 Answers

4
votes

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