Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 10 - detect if image exists on client side only, else default image

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>
like image 876
E-jarod Avatar asked Oct 21 '25 14:10

E-jarod


1 Answers

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

like image 123
yurzui Avatar answered Oct 23 '25 04:10

yurzui