Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


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


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.

    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.

    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.

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

    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.

    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.

    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.

    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.