Let’s start with a common use case. You have some data you get from external source (e.g. by calling API). You want to display it on screen.

However, instead of displaying it on the same component, you would like to pass the data to a child component to display.

The child component might has some logic to pre-process the data before showing on screen.

Our Example

For example, 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 and posts

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? Let’s code!

Our Post Interfaces and Data

Let’s start with interfaces.

// post.interface.ts

// each post will have a title and category
export interface Post {
    title: string;
    category: string;
}

// grouped posts by category
export interface GroupPosts {
    category: string;
    posts: Post[];
}

Copy

Here is our mock posts data assets/mock-posts.json.

[
    { "title": "Learn Angular", "type": "tech" },
    { "title": "Forrest Gump Reviews", "type": "movie" },
    { "title": "Yoga Meditation", "type": "lifestyle" },
    { "title": "What is Promises?", "type": "tech" },
    { "title": "Star Wars Reviews", "type": "movie" },
    { "title": "Diving in Komodo", "type": "lifestyle" }
]

#angular

3 Ways to Pass Async Data to Angular 2+ Child Components
1.45 GEEK