Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - How to load image with spinner in angular2

my app got many images with descriptions. When user navigates these text is coming first and image is loading 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 spinner and track the image is loaded or not and display it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...