I have a child Calendar Component that receives events from his father through an input field.
@Input() private events: any[];
When the month changes the parent gets new events from an API Service and calls the child component to show them.
private populateEventsForCurrentMonth() {
return this.calendarService.getEventsAsAdmin(this.getCurrentStartDate(),
this.getCurrentEndDate())
.then((evts) => {
this.events = evts;
this.calendarChild.selectEventDaysIfApplies();
})
.catch((err) => {
console.log('error getting events', err);
});
}
But when the child tries to access the events they haven't been updated!
My workaround was wrapping the child function in a timeout of 0 milliseconds to put the entire execution at the end of the event loop.
public selectEventDaysIfApplies() {
setTimeout(() => {
if (this.events) {
this.events.forEach((event) => {
let eventDate = new Date(event.starts_at);
if (this.datesBelongToSameMonth(eventDate, this.currentDate)) {
let dayWithEvent = this.days.find( (day) => {
return day.number == eventDate.getDate();
});
if (!dayWithEvent.selected) {
dayWithEvent.hasEvent = true;
}
}
});
}
}, 0);
}
Is there a better way of doing it? Maybe an Angular best practice that I should be implementing?
Thanks!
.then((evts) => {
means "later" or "eventually". The method is async because it takes a certain amount of time to get the result, the browser (JS) is not blocking until the data arrives, but instead continues execution, and when the data finally arrives, the function passed tothen(...)
is executed. – EloignngOnChanges()
and use theSimpleChange
object, Angular should know when the data is ready. It seems better than asetTimeout()
. – Nidianidicolous