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