I am fetching a large number of image URLs from an API and display them in a angular 2 web application. Some of the URLs are broken and i want to replace them with a default
You can use onError
event this way to handle invalid url
or broken url
.
<img [src]="invalidPath" onError="this.src='images/angular.png'"/>
This way you can directly assign img path to src with onError event
Listen to the error
event of the image element:
<img [src]="someUrl" (error)="updateUrl($event)">
where updateUrl(event) { ... }
assigns a new value to this.someUrl
.
Plunker example
If you want to check in code only you can use the method explained in Checking if image does exists using javascript
@Directive({
selector: 'img[default]',
host: {
'(error)':'updateUrl()',
'[src]':'src'
}
})
class DefaultImage {
@Input() src:string;
@Input() default:string;
updateUrl() {
this.src = this.default;
}
}
Directive Plunker example
A perfect Angular 8 directive:
import {AfterViewInit, Directive, ElementRef, Input} from '@angular/core';
@Directive({
selector: '[appImage]'
})
export class ImageDirective implements AfterViewInit {
@Input() src;
constructor(private imageRef: ElementRef) {
}
ngAfterViewInit(): void {
const img = new Image();
img.onload = () => {
this.setImage(this.src);
};
img.onerror = () => {
// Set a placeholder image
this.setImage('assets/placeholder.png');
};
img.src = this.src;
}
private setImage(src: string) {
this.imageRef.nativeElement.setAttribute('src', src);
}
}
Now, HTML will be:
<img [src]="'/some/valid-image.png'" appImage>
I found a very simple solution that worked for me. This doesn't check for 404's however I had objects that possibly had and .image attribute. I know this isn't the answer to his question but hopefully it helps some one out there.
<img class="list-thumb-img" [attr.src]="item.image?.url ? item.image.url : 'assets/img/140-100.png'">
If you want to change an image that is not loading or the source is broken... Angular 8, just have to change the src of this target for a default asset:
Component HTML
<... [src]="person.pictureUrl" (error)="pictNotLoading($event)" >
Component TS
pictNotLoading(event) { event.target.src = 'assets/nopicture.png'; }
You can simply use a ternary operator for this use case. I am assuming that you are getting the responses from a remote server
<img src="{{ res.image ? res.image : onErrorFunction() }}"
If you don't want to have the image from server write the path in single quotes ''.
Here if the link is broken then it will go to onErrorFunction if it isn't broken the res.image will be loaded.