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
letstops the issue you are talking about and IMK,setValue()is not an async call, so that shouldn't event be a problem. What is the issue you are facing can you explain more, I didn't get the question.TeamWorkingDate, a FormGroup in a FormArray (7 appended OnInit) todate,date+1 day, etc but I'm just getting this set todate+7 daysfor all of them.date.clone()? Does it really gives a newDate and doesn't modify the existing date?