Reputation: 1973
I have a component and try to assign to an object some props. On try no1. I have no err but nothing is displayed on UI and in try no2 I have an error "cannot set property number of undefined".
days: Day[] = [];
now: Date = new Date();
ngOnInit() {
this.days = [];
for (let i = 0; i < this.numberOfDaysCurrentMonth; i++) {
// try no.1
this.days.forEach(x => x.number = i);
this.days.forEach(x => x.weekDay = new Date(this.currentYear, this.currentMonth - 1, i).getDay());
this.days.forEach(x => x.name = '')
//try no.2
this.days[i].number = i;
this.days[i].weekDay = new Date(this.currentYear, this.currentMonth - 1, i).getDay());
this.days[i].name = ''
}
and
export class Day {
number: number;
weekDay: number;
name: string;
}
Upvotes: 1
Views: 250
Reputation: 1673
What you need to do is add the day to the days array when you loop over this.numberOfDaysCurrentMonth
ngOnInit() {
this.days = [];
for (let i = 0; i < this.numberOfDaysCurrentMonth; i++) {
let day = {
number: i,
weekDay: new Date(this.currentYear, this.currentMonth - 1, i).getDay(),
name: ''
}
this.days.push(day);
}
}
Your try with this.days.forEach
doesn't do anything because it loops over each object in the days array which is empty.
Similarly, this.days[i]
is really undefined because the array is empty.
Upvotes: 4
Reputation: 343
Your array is never filled with any entries. this.days.forEach is going to do something for every item in the array, but as the array is empty, i doesn't do anything.
You should populate the array first and then use forEach on it.
Upvotes: 0