How to load image using counter in angular2

Many images with descriptions appeared in my application. When the user moves, this text comes first, and the image is loaded with some delay. I would like to add a spinner here. A directive that shows the spinner when loading an image and shows an image like

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

How to add a spinner and track the image loaded or not and display it?

+4
source share
3 answers

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

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

gif ( , ), loading === true, , img [hidden]="true/false", src, onLoad (load) :

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

, AngJobs, IMO.

PS: [hidden]="boolean" *ngIf - gotcha, http://angularjs.blogspot.com/2016/04/5-rookie-mistakes-to-avoid-with-angular.html, , , .

+8

, , ,

 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);
+1

I think the easiest way is to use an event onErrorfor the img element. You can use it like:

<img [src]="image.src" onError="this.src='assets/my/fancy/loader.gif';">
+1
source

All Articles