Angular 2 - Check if image url is valid or broken

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

    
    

提交回复
热议问题