How to load image with spinner in angular2

被刻印的时光 ゝ 提交于 2019-12-03 07:08:55

In your controller, add a function to 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 has 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 to http://angularjs.blogspot.com/2016/04/5-rookie-mistakes-to-avoid-with-angular.html to understand why and for a solution on how to apply it safely.

You dont need a function here, just add to your component:

imageLoader = true;

In template add following:

<div [hidden]="!imageLoader">Loading...</div>
<img [hidden]="imageLoader" src=".../image.png" (load)="this.imageLoader = false;" />

... as you see, there is text instead of a gif beacause actually a loading animation gif also must be loaded. In some cases this could take much more time, than loading the image itself.

If the gif is loaded already you can use:

<img [hidden]="!imageLoader" src=".../loading_spinner.gif" />
<img [hidden]="imageLoader" src=".../image.png" (load)="this.imageLoader = false;" />

The idea is to display the spinner by default, create a separate Image object that would be displayed when load is complete

 var img = new Image();

    /// set handler and url
    img.onload = onloadHandler;
    img.src = imageURLs[i];

    /// if image is cached IE (surprise!) may not trigger onload
    if (img.complete) onloadHandler().bind(img);

I think the most easiest way is to use the onError event on the img element. You can use it Like:

<img [src]="image.src" onError="this.src='assets/my/fancy/loader.gif';">
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!