How to show a placeholder image before the actual image loads in ionic


#1

Good day,

I’m working on an Ionic application and I’m loading images dynamically from a JSON feed. I would like that when the images are being pulled in from the external URL that a placeholder image shows in its place, thereafter, the placeholder image should then be replaced by the “real” image once its loaded.

An example of my current situation is:

<ion-card *ngFor="let item of items"...
 <img [src]="item.picture" />

Thanks & Regards.


#2

Hi @APPi_Mobile,

While you are fetching the images from backend using API, before you got the image you can set one variable as an flag and set it to true and while that variable is true display your place holder and after you got the data set that variable to false so that you can display the actual image over there.


#3

@addwebsolution thanks for your feedback! Are you able to demonstrate your answer in oder for me to fully understand your response. Thanks.


#4

home.ts (as example)

export class HomePage {
    placeholder;

    constructor(){
        this.placeholder = "IMG_PATH";
        this.createCall();
    }
    
    createCall(){

       var headers = new Headers();
        headers.append('Content-Type', 'application/x-www-form-urlencoded');

        this.http.post('URL', {headers: headers})
        .subscribe(res => {

            this.placeholder = res.json();

        }, (err) => {

            console.log(err);

        });
    }

}

home.html (as example)

<img src="{{ placeholder }}">

I hope this information helps you further with your problem.


#5

It would seem considerably cleaner and simpler to me to just set item.picture to the placeholder URL at the time item is born, and swap it out once the actual image is available. The template needs no modification at all in this scenario.

This is a bad habit. Once you start dealing with DomSanitizer, you will bang your head into this.