Search code examples
ionic-frameworkion-slides

How to add placeholder image to ion-slides in ionic 3 app?


I want to add placeholder image to my ion-slider before my images are loaded dynamically. Here is my code:

HTML

<div *ngIf="service?.banners" class="home-banners">
        <ion-slides  pager="true"  spaceBetween="5" loop="true" autoplay="3900">
            <ion-slide *ngFor='let value of service.banners'>
                
                 <img src="{{value}}"> 
                </ion-slide>
        </ion-slides>
    </div>

SCSS

.home-banners {
    ion-slides {

        height: 50%; 
        padding-left: 5px;
        padding-right: 5px;
         padding-top: 5px;

    }
}

Solution

  • If you pursue lazy loading approach you could do something like this below:

    • add a div wrapper and make its background grey (e.g. skeleton UI) or point it to URL (i used external but you can use an img from local assets)
    • use attribute binding condition to only set src of actual img if it is active slide or +1 index from it (you can alter conditions you need here)
    • on load of actual image - set a flag in your data model to keep src intact if the image was already loaded

    html template:

    <ion-content>
      <div>
        <ion-slides #sliders pager="true" spaceBetween="5">
          <ion-slide *ngFor='let imgItem of images; index as i;'>
            <div class="lazySlide">
              <img class="lazyImage" [src]="(sliders.getActiveIndex() == i || sliders.getActiveIndex() == i-1) || imgItem.loaded? imgItem.source:''" (load)="imgItem.loaded=true">
            </div>
          </ion-slide>
        </ion-slides>
      </div>
    </ion-content>
    

    Component code example:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
    
      images: Array<{ loaded: boolean, source: string}> = [
        {
          loaded: false,
          source: "https://placeimg.com/1000/1000/nature"
        },
        {
          loaded: false,
          source: "https://placeimg.com/1000/1000/people"
        },
        {
          loaded: false,
          source: "https://placeimg.com/1000/1000/tech"
        },
        {
          loaded: false,
          source: "https://placeimg.com/1000/1000/architecture"
        },
        {
          loaded: false,
          source: "https://placeimg.com/1000/1000/animals"
        }
      ]
    
      constructor(
      ) {
      }
    
    }
    

    scss:

    page-home {
        .lazyImage {
            width: 100%;
            height: 100%;
        }
        .lazySlide {
            background: url(http://via.placeholder.com/1000x1000);
        }
    }