Angular2: Show placeholder image if img src is not valid

Viewed 78620

Goal: Load an image with a dynamic source. If no image is found, then load a placeholder image instead.

This should demonstrate what I'm trying to do, but I don't know how to conditionally set validImage based on whether the first img src is valid.

<img *ngif="validImage" class="thumbnail-image" src="./app/assets/images/{{image.ID}}.jpg" alt="...">
<img *ngif="!validImage" class="thumbnail-image" src="./app/assets/images/placeholder.jpg" alt="...">

validImage should be true if src="./app/assets/images/{{image.ID}}.jpg" returns an image. Otherwise it would return false and only the second img tag should show.

There are obvious work arounds like storing a list of all valid image sources, but I'm thinking there is a better way to accomplish this.

Any suggestions on the best way to implement this in Angular2 would be greatly appreciated.

8 Answers

The following approach also works if you want to handle the error in you class:

In your template:

<img [src]='varWithPath' (error) ="onImgError($event)">

In your class:

onImgError(event) { 
    event.target.src = 'assets/path_to_your_placeholder_image.jpg';
}

I Just did this :

In my HTML FILE wrote this

<div 
   (click)="getInfo(results[movie].id)"
   *ngFor="let movie of (results | key:'10')" 
    class="card" style="margin-top:7%;">
 <img [src]="getImage(results[movie])" alt="" class="card-img-top pointer"></div>

I called a function that is in my component.ts and pass the object wheres my url as a parameter

getImage(result){
if(result.poster_path){
  return this.imageURL+(result.poster_path);
}else return "./assets/noFound.jpg"

Heres my function , first I verify if the object image url is different from null if is true then I return the image url else i return my default "noFound" image that is in my app assets.
Hope it helps!

Related