0

I'm trying to loop though a FormArray setting values. Fairly new to javascript.

Below TeamWorkingDate is set to the same date for each of the 7 FormGroup's in the Team FormArray, and is set to the last in the loop, date + 7 days.

I've tried many variations of forEach and answers @ JavaScript closure inside loops – simple practical example as I believe this must be some closure issue.

My understanding of closures is limited despite reading up on this. In this instance - is it that setValue has access to the variable i outside the function call and so is 'seeing' i = 7? I thought let stops this issue?

  setDates(date: moment) {
    var arr = [];
    for(let i = 0; i < 7; i++) {
      let nextDate = date.clone().add(i, 'day');
      arr.push(nextDate);
      (<FormArray>this.myForm.get('Teams')).controls[i]
        .get('TeamWorkingDate').setValue(arr[i]);
    }
  }

My Form:

  ngOnInit() {
    this.myForm = this.fb.group({
      Teams: this.fb.array([])
    });
    const team = this.fb.group({
      TeamWorkingDate: '',
      ...
    })
    for (let i = 0; i < 7; i++) {
      (<FormArray>this.myForm.get('Teams')).push(team);
    }
  }

EDIT: changed to let nextDate = date.clone().add(i, 'day'); instead of var

Andrew Allen
  • 6,512
  • 5
  • 30
  • 73

1 Answers1

2

Currently all the formGroups in the formArray are pointing to the same FormGroup reference, so changing value at any index will effectively update the same group. Create and push new FormGroups in the formArray.

 ngOnInit() {
    this.myForm = this.fb.group({
      Teams: this.fb.array([])
    });
    for (let i = 0; i < 7; i++) {
      const team = this.fb.group({
      TeamWorkingDate: '',
        ...
      })
      (<FormArray>this.myForm.get('Teams')).push(team);
    }
  }
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51