Jecelyn Yeen

@jecelynyeen

3 Ways to Pass Async Data to Angular + Child Components

For Angularjs or Angular 1.x posts, it will be stated 1.x explicitly, else it’s always the latest version of Angular.

Use Case

Let’ say you have a blogger component that will display blogger details and her posts. Blogger component will gets the list of posts from API.

Instead of writing the logic of displaying the posts in the blogger component, you want to reuse the posts component that is created by your teammate, what you need to do is pass it the posts data.

The posts component will then group the posts by category and display accordingly, like this:

blogger component

Isn’t That Easy?

It might look easy at the first glance. Most of the time we will initiate all the process during our component initialization time — during ngOnInit life cycle hook (refer here for more details on component life cycle hook).

In our case, you might think that we should run the post grouping logic during ngOnInit of the posts component.

However, because the posts data is coming from server, when the blogger component passes the posts data to posts component, the posts component ngOnInit is already fired before the data get updated. Your post grouping logic will not be fired.

How can we solve this? Please read further in my Scotch post.

More by Jecelyn Yeen

Topics of interest

More Related Stories