angularangular2-directives

How to load image with spinner in Angular2


My app has many images with descriptions. When user navigates, the text appears first and the image loads with some delay. I would like to add a spinner here. A directive which shows spinner while loading the image and shows image like:

<myimgdir [src]='myimage.png'></myimgdir>

How to add the spinner, track image loading, and display it accordingly?


Solution

  • In your controller, add a function to handle the onLoad event, setting the state to {loading: false}:

    loading: boolean = true
    onLoad() {
        this.loading = false;
    }
    

    In your template, render a loading GIF (or whatever you want) while the state is loading === true. The tricky part is that you should just hide the img element with [hidden]="true/false" as opposed to prevent it from rendering so it will actually load the src, then just bind the onLoad function in your controller to the (load) event on the actual image:

    <img *ngIf="loading" src="/assets/loading.gif" alt="loading" />
    <img [hidden]="loading" (load)="onLoad()" src="{{ source }}" />
    

    This solution is functionally the same as AngJobs's, but it's more declarative and a little less cumbersome IMO.

    PS: Using [hidden]="boolean" instead of *ngIf is a bit of a gotcha, you should look here to understand why and for a solution on how to apply it safely.