Angular - Input is not immediately available to the child component, why?

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!

+5
source share
1 answer

Data is not yet available, as this function is processed synchronously:

 this.events = evts; this.calendarChild.selectEventDaysIfApplies(); 

Immediately after installing this.events child components run their selectEventDaysIfApplies() method. This happens before Angular change detection is performed.

In my opinion, the parent component should not be aware of any checks and changes that its child components must perform.

A better solution would be to use the OnChanges lifecycle hook, which is triggered whenever a component's input changes.

 ngOnChanges(changes: SimpleChanges) { this.selectEventDaysIfApplies(); } 

If your component has more than one input, you can check which one has been changed.

Read more about this in the docs .

+1
source

Source: https://habr.com/ru/post/1271337/


All Articles