I have a child component of Calendar that receives events from its father through an input field.
@Input() private events: any[];
When the month changes, the parent receives new events from the API service and calls the child component to display 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 a child tries to access events, they are not updated!
My workaround was to wrap the child function for 0 milliseconds to complete all 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 to do this? Maybe the best Angular practice I should implement?
Thanks!
Willa source share