Angular 2 - Check if image url is valid or broken

My example on angular 4

<img [src]="img" (error)="img.src = errorImg" #img>
  1. Where img - path to image;
  2. error - error emmit
  3. errorImg - path to default img
  4. #img - link to img object

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


You can use onError event this way to handle invalid url or broken url.

  • https://plnkr.co/edit/fD8zxd?p=preview
<img [src]="invalidPath" onError="this.src='images/angular.png'"/> 

This way you can directly assign img path to src with onError event