Search code examples
javascriptangulartypescriptionic-frameworkionic4

How to set a default image in an ionic app


I'm trying to add a default image to an ionic app. Currently I'm getting images inside the app through a link which is in the rows of the tables in the database. However if the image does not exist anymore or the link is broken I want the app to display a default/fall-back image and not this default ripped apart painting icon.

This is one of the methods I have tried getting it to work but it doesn't.

        <ion-card transparent class="detailView" *ngFor="let act of activities">
        <img class="img" src="{{act.image}}"
        onerror="this.src='assets/imgs/defualt.jpg';" alt = "Missing Image" />

{{act.image}} talks to the database, to be precise to the activity table in the database and extracts the image links. How do I implement a default option if the image can't be displayed?

A few extra tidbits; the app is written with Ionic Framework and implements the use of Typescript, Sass and Angular.


Solution

  • Here is what you can do.

    <img [src]="act.image" alt="Missing image" onerror="this.onerror=null;this.src='assets/imgs/default.jpg';" />
    

    You’re using a locally saved file as default, so it’s unlikely to happen, but for good practice, clear “onerror” to avoid an endless loop in case the “fallback” image doesn’t exist.