Angular2: Show placeholder image if img src is not valid

后端 未结 8 1735
迷失自我
迷失自我 2020-12-12 12:55

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

相关标签:
8条回答
  • 2020-12-12 13:30

    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';
    }
    
    0 讨论(0)
  • 2020-12-12 13:30
    <img class="thumbnail-image" src="getImage()" alt="...">
    
    getImage():string{  //I don't know how would you handle your situation here. But you can think of it.
    
      if (this.validImage) // I don't know how would you manage validImage here.
      {
         return this.validImagePath;
      }
    
       return this.placeholderImagePath;
    }
    
    0 讨论(0)
提交回复
热议问题