Angular 2 - Check if image url is valid or broken

后端 未结 9 2003
感情败类
感情败类 2020-11-29 19:31

I am fetching a large number of image URLs from an API and display them in a angular 2 web application. Some of the URLs are broken and i want to replace them with a default

9条回答
  •  伪装坚强ぢ
    2020-11-29 20:11

    Listen to the error event of the image element:

    
    

    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

提交回复
热议问题