I need to know how to detect if an image exists, on client-side only, with Angular. I have heard that we can set a default image with the timeout function, but I don't know how to catch 404 errors.
I need to write the code on the getResourceImg() only, as the angular's style guide says
resource-ui.component.ts
@Input() resource: IResourcePublished;
// ...
resourceImgUrlLogoDefault: string = 'assets/images/logo_default.png';
resourceImgUrl: string;
constructor(private modalService: NgbModal) {}
ngOnInit(): void {
this.resourceImgUrl = this.getRessourceImg(this.resource);
}
getResourceImg(resource: IResourcePublished): string {
return 'assets/images/screen-resources/' + resource.id + '.png';
}
//..
Here's the template (generated with a *ngFor="let resource of resources") :
resource-ui.component.html
<div class="card" [style.background]="categoryColor">
<div class="card-header" ngbTooltip="More infos" (click)="openResourceDetails()">
<img
class="layout-img img-fluid"
[src]="resourceImgUrl"
alt="resource-{{resource.id}}"
/>
</div>
<!-- ... -->
</div>
You can create reusable directive like:
fallback-img.directive.ts
import { Directive, Input, HostBinding, HostListener } from '@angular/core';
@Directive({
selector: 'img[fallback]'
})
export class FallbackImgDirective {
@Input()
@HostBinding('src')
src: string;
@Input() fallback: string;
@HostListener('error')
onError() {
this.src = this.fallback;
}
}
Usage
<img src="http://unknown/404.jpg" fallback="https://via.placeholder.com/150" alt="">
Ng-run Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With