Skip to content

Instantly share code, notes, and snippets.

@eneajaho
Created November 25, 2021 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eneajaho/540f279686fede9160faa087a9bdd4c9 to your computer and use it in GitHub Desktop.
Save eneajaho/540f279686fede9160faa087a9bdd4c9 to your computer and use it in GitHub Desktop.
Default image on error - Angular directive
import { Directive, HostListener, Input, NgModule } from '@angular/core';
@Directive({
selector: '[defaultImageOnError]'
})
export class DefaultImageOnErrorDirective {
@Input() defaultImageOnError: string;
@HostListener('error', ['$event'])
handleError(event: ErrorEvent): void {
(event.target as HTMLImageElement).src = this.defaultImageOnError;
}
}
@NgModule({
exports: [DefaultImageOnErrorDirective],
declarations: [DefaultImageOnErrorDirective],
})
export class DefaultImageOnErrorDirectiveModule {}
@eneajaho
Copy link
Author

Usage:

export class TestComponent {
  imageUrl = 'http://helloworld.com'; // this will throw error when loaded as image
}
 <img
  [src]="imageUrl"
  defaultImageOnError="assets/error.png"
  alt="Hello world"
  loading="lazy" />

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment