3

Currently I have this in my component

<img *ngIf="(showImage$ | async)" [alt]="image.alt [title]="image.title" [src]="image.src" (load)="imageHasBeenLoaded($event)" />

and the I do some actions in the imageHasBeenLoaded() function... but how do I handle cases where it fails? eg. if the image request returns a 404?

3 Answers 3

6

you can use (error) that way to set default image in case of 404, you can set a default pic from asset or from placeholder

<img [src]="slide.img" (error)="slide.img='./assets/img/default.jpg'">
Sign up to request clarification or add additional context in comments.

2 Comments

Thx.. have been searching for the other methods like (load) but found nothing in the angular docs.. do you know where I can find some references?
load is use to know when the img is completely loaded, it will be useful to show a loading spinner till the img is loaded but i don't think that you can handle fails inside
0

If you get 404. I'm pretty sure you should have had mistake in path or the name of the file. Or you didn't put them in the path that you indicated. like ./assets/img/default.jpg.

My code from my project looks like.

<mat-card *ngFor="let respo of work.Used" fxFlexAlign="auto" style="background:#E0E0E0; height:40px; margin-left: 5px; margin-bottom: 5px; text-align: center; padding: 5px;">
    <img style="height: 40px; margin:auto;" src={{respo}} alt="Photo of a Shiba Inu">
  </mat-card>

I give sources for each image through json file that finally gets to this part of the code and ends up at src={{respo}}. I think you should be using {{}} too. And if you get error it should mean that you made mistake spelling. be aware the path and name are case sensitive.

3 Comments

obviously the file is missing ;) but files can be removed without the database being updated so there is not an angular code error here ;) .. so why do you thing I should use {{}}? It's just another way to bind stuff?
I guess I misunderstood your question. To be honest the only reason I suggested {{}} is because it worked for me. :D
hehe.. well then I might enlighten you on this topic. {{}} can only be used for strings.. so if you have a boolean then you must use the property binding [].. personally I find the property binding easier to read ;)
0

you can bind imageHasBeenLoaded() method to error event which is triggered if an error occurs while loading an external file (e.g. a document or an image).

(error)="imageHasBeenLoaded($event)"


<img *ngIf="(showImage$ | async)" [alt]="image.alt [title]="image.title" [src]="image.src" (error)="imageHasBeenLoaded($event)" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.