Angular 2 - Check if image url is valid or broken

后端 未结 9 1891
感情败类
感情败类 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:06

    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

0 讨论(0)
  • 2020-11-29 20:11

    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

    0 讨论(0)
  • 2020-11-29 20:12

    A perfect Angular 8 directive:

    import {AfterViewInit, Directive, ElementRef, Input} from '@angular/core';
    
    @Directive({
        selector: '[appImage]'
    })
    export class ImageDirective implements AfterViewInit {
    
        @Input() src;
    
        constructor(private imageRef: ElementRef) {
        }
    
        ngAfterViewInit(): void {
            const img = new Image();
            img.onload = () => {
                this.setImage(this.src);
            };
    
            img.onerror = () => {
                // Set a placeholder image 
                this.setImage('assets/placeholder.png');
            };
    
            img.src = this.src;
        }
    
        private setImage(src: string) {
            this.imageRef.nativeElement.setAttribute('src', src);
        }
    }
    

    Now, HTML will be:

    <img [src]="'/some/valid-image.png'" appImage>
    
    0 讨论(0)
  • 2020-11-29 20:14

    I found a very simple solution that worked for me. This doesn't check for 404's however I had objects that possibly had and .image attribute. I know this isn't the answer to his question but hopefully it helps some one out there.

    <img class="list-thumb-img" [attr.src]="item.image?.url ? item.image.url : 'assets/img/140-100.png'">
    
    0 讨论(0)
  • 2020-11-29 20:17

    If you want to change an image that is not loading or the source is broken... Angular 8, just have to change the src of this target for a default asset:

    • Component HTML

      <... [src]="person.pictureUrl" (error)="pictNotLoading($event)" >

    • Component TS

      pictNotLoading(event) { event.target.src = 'assets/nopicture.png'; }

    0 讨论(0)
  • 2020-11-29 20:18

    You can simply use a ternary operator for this use case. I am assuming that you are getting the responses from a remote server

    <img src="{{ res.image ? res.image : onErrorFunction() }}"
    

    If you don't want to have the image from server write the path in single quotes ''.

    Here if the link is broken then it will go to onErrorFunction if it isn't broken the res.image will be loaded.

    0 讨论(0)
  • 提交回复
    热议问题