Search code examples
angularimageionic2srcng-template

Fallback image with condition on error in Ionic 2 Angular 4


I have a tag which hold an image source. I also wrote an error case if the image fails. Below is my code

<div class="column thumbnail"><img class="posterThumbNail" [src]="item.imageUrl" onError="this.src='./assets/imgs/placeholder.png';" /></div>

Can I have a condition inside this onError so that, depending on the thumbnail category, I can show different placeholder image with respect to the category. Expecting something like,

<div class="column thumbnail"><img class="posterThumbNail" [src]="item.imageUrl" onError="errorPlaceHolder" /></div>

<ng-template #errorPlaceHolder>
 <div [ngSwitch]="item.category">
    <template [ngSwitchCase]="foo">
        <div>./assets/imgs/placeholderFoo.png</div>
    </template>
    <template [ngSwitchCase]="bar">
        <div>./assets/imgs/placeholderBar.png</div>
    </template>
    <template [ngSwitchCase]="cat">
        <div>./assets/imgs/placeholderCat.png</div>
    </template>¯
    <template [ngSwitchCase]="dog">
        <div>./assets/imgs/placeholderDog.png</div>
    </template>
</div>
</ng-template>

I know the above code in syntactically not correct. I am looking for solution matching my above snippet. Thanks.


Solution

  • You can also reverse the logic and replace the placeholder only when the main image is loaded. This can be done with ngif and (load). Also how about putting the logic in the class instead of in the template? Easier to debug? It can be finished with a help on an additional array to keep the track of loaded images. This array could be merged with the original array, depending how you get it and how you manage it.

    Class:

    loaded = [false, false, false]; // should have items length
    ...
    getReplacementImage(category) {
    switch (category) {
      case "dog":
        return "dogImage";
      case "cat":
        return "catImage"
      default:
        return "placeholderImage"
    }
    

    Html:

    <... *ngFor="let item of items; let i = index">
    
        <img [class.image-error]="!loaded[i]" ... [src]="item.image" (load)='loaded[i]=true'>
    
        <img *ngIf="!loaded[i]" ... [src]="getReplacementImage(item.category)">
    
    </...>
    

    CSS:

    .image-error {
      display:none; // to hide the placeholder image
    }
    

    DEMO