Show a loading indicator in Angular using *ngIf/else, the as keyword and the async pipe

Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 6 years ago

The network may be unreliable and loading data may take time. Thus it is important to give the user some feedback about what's going on as fast as possible. In this lesson we learn how to leverage the else block of the *ngIf directive to show a simple loading indicator.

[00:00] Here we see a component, a person detail, which has a button. Whenever the user clicks the button here an HTTP request is being issued to some JSON file.

[00:10] The result is stored here in an observable which is then bound directly in the template of the component by using an async pipe here, and by storing the result in that person's template variable.

[00:23] Let's for a second inspect here the network panel. What we would like to do is to throttle the network connection to its low 3G connection. Now, when we clicked that button we can see that the request is being made, but it takes a couple of seconds here until something's been displayed.

[00:43] While that loading is going on, nothing's being displayed to the user, actually. We would like to change that. Let's see how.

[00:52] Basically, as long as that observable isn't resolved, so the data hasn't come back from the back end, we would like to show some other template. Once it gets resolved, it should actually show this template inside here with the correct data.

[01:06] First, we can use the NG template. Inside here we simply show something like loading person dot, dot, dot. Now, this template can be attached to this NG if part here by using the new introduced as clause, so we can use as.

[01:27] Now we see we have to give that template a name. Let's call it person.loading. We can now then reference that person loading up there. Basically, as long as this request goes on, this part will be shown because this here resolves to null. Otherwise, this part is here showing which correctly in this place, the correct data.

[01:49] Let's store this. Now let's again open up here our window. Let's throttle it here to our 3G connection. Now if we click, we see that loading person. Once it resolves, it shows the correct data.