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>