Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2 onError image binding

I'm wondering if we can bind or interpolate the onError on the image tag using angular2,

on the app.component.ts:

imageUrl:string;

  constructor( ) {
      this.imageUrl = 'graphics/placeholder.gif';
   }

on the app.component.html:

<img class="img-responsive" [src]="'graphics/image-1.jpg'" onError="imageUrl"/>

The method below works.

<img class="img-responsive" [src]="'graphics/image-1.jpg'" onError="this.src='graphics/placeholder.gif'"/>

But as we using a many images on the app and I would like to make it a simple dynamic solution, I found this answer as well,

Angular 2 - Check if image url is valid or broken

but for some reason is not working, I don't know what I'm doing wrong here

like image 943
jcdsr Avatar asked Feb 09 '17 11:02

jcdsr


2 Answers

It was almost complete he just forgot to change the image after the event.

errorHandler(event) {
   console.debug(event);
   event.target.src = "https://cdn.browshot.com/static/images/not-found.png";
}

Here is the link

like image 160
Americo Arvani Avatar answered Oct 31 '22 14:10

Americo Arvani


component.ts

onImgError(event){
 event.target.src = './assets/imgs/altImg.png'
//Do other stuff with the event.target
}

component.html

 <img [src]="imgUrl" (error)="onImgError($event)">
like image 26
Saurabh47g Avatar answered Oct 31 '22 15:10

Saurabh47g