——————————————————————
3 Ways to Pass Async Data to Angular 2+ Child Components
While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.
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:
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!
- Demo: https://ng-musing.firebaseapp.com/three-ways
- Github: https://github.com/chybie/ng-musing/tree/master/src/app/three-ways
Our Post Interfaces and Data
Let’s start with interfaces.
Here is our mock posts data assets/mock-posts.json
.
Blogger Component
Let’s take a look at our blogger component.
We will get our mock posts data by issuing a HTTP GET
call. Then, we assign the data to posts
property. Subsequently, we bind posts
to posts component in our view template.
Please take note that, usually we will perform HTTP call in service. However, since it’s not the focus of this tutorial (to shorten the tutorial), we will do that it in the same component.
Posts Component
Next, let’s code out posts component.
We have an input called data
which will receive the posts data from parent component. In our case, blogger component will provide that.
You can see that we implement two interfaces OnInit
and OnChanges
. These are the lifecycle hooks that Angular provide to us. We have not done anything in both ngOnInit
and ngOnChanges
just yet.
The groupByCategory
function is our core logic to group the posts by category. After the grouping, we will loop the result and display the grouped posts in our template.
Remember to import these components in you module (e.g. app.module.ts
) and add it under declarations
.
Save and run it. You will see a pretty empty page with the blogger name only. That’s because we have not code our solution yet.
Solution 1: Use *ngIf
Solution one is the easiest. Use *ngIf
in blogger component to delay the initialization of posts components. We will bind the post component only if the posts variable has a value. Then, we are safe to run our grouping logic in posts component ngOnInit
.
Our blogger component:
Our posts component.
A few things to note:
- Since the grouping logic runs in
ngOnInit
, that means it will run only once. If there’s any future updates ondata
(passed in from blogger component), it won’t trigger again. - Therefore, if someone change the
posts: Post[]
property in the blogger component toposts: Post[] = []
, that means our grouping logic will be triggered once with empty array. When the real data kicks in, it won’t be triggered again.
Solution 2: Use ngOnChanges
ngOnChanges
is a lifecycle hook that run whenever it detects changes to input properties. That means it’s guaranteed that everytime data input value changed, our grouping logic will be triggered if we put our code here.
Please revert all the changes in previous solution
Our blogger component, we don’t need *ngIf
anymore.
Our posts component
Please notes that changes
is a key value pair object. The key is the name of the input
property, in our case it’s data
. Whenever writing code in ngOnChanges
, you may want to make sure that the logic run only when the target data changed, because you might have a few inputs.
That’s why we run our grouping logic only if there are changes in data
.
One thing I don’t like about this solution is that we lose the strong typing and need to use magic string “data”. In case we change the property name data
to something else, we need to remember to change this as well.
Of course we can defined another interface for that, but that’s too much work.
Solution 3: Use RxJs BehaviorSubject
We can utilize RxJs BehaviorSubject
to detect the changes. I suggest you take a look at the unit test of the official document here before we continue.
Just assume that BehaviorSubject
is like a property with get
and set
abilities, plus an extra feature; you can subscribe to it. So whenever there are changes on the property, we will be notified, and we can act on that. In our case, it would be triggering the grouping logic.
Please revert all the changes in previous solution
There are no changes in our blogger component:
Let’s update our post component to use BehaviorSubject
.
First of all, if you are not aware, Javacript supports getter
and setter
like C# and Java, check MDN for more info. In our case, we split the data
to use getter
and setter
. Then, we have a private variable _data
to hold the latest value.
To set a value to BehaviorSubject
, we use .next(theValue)
. To get the value, we use .getValue()
, as simple as that.
Then during component initialization, we subscribe to the _data
, listen to the changes, and call our grouping logic whenever changes happens.
Take a note for observable
and subject
, you need to unsubscribe to avoid performance issues and possible memory leaks. You can do it manually in ngOnDestroy
or you can use some operator to instruct the observable
and subject
to unsubscribe itself once it meet certain criteria.
In our case, we would like to unsubscribe once the groupPosts
has value. We can add this line in our subscription to achieve that.
With this one line .takeWhile(() => !this.groupPosts)
, it will unsubscribe automatically once it’s done. There are other ways to unsubscribe automatically as well, e.g take
, take Util
, but that’s beyond this topic.
By using BehaviorSubject
, we get strong typing, get to control and listen to changes. The only downside would be you need to write more code.
Which One Should I Use?
The famous question comes with the famous answer: It depends.
Use *ngIf
if you are sure that your changes run only once, it’s very straightforward. Use ngOnChanges
or BehaviorSubject
if you want to listen to changes continuously or you want guarantee.
- Demo: https://ng-musing.firebaseapp.com/three-ways
- Github: https://github.com/chybie/ng-musing/tree/master/src/app/three-ways
That’s it. Happy Coding!