Angular2: Show placeholder image if img src is not valid

后端 未结 8 1765
迷失自我
迷失自我 2020-12-12 12:55

Goal: Load an image with a dynamic source. If no image is found, then load a placeholder image instead.

This should demonstrate what I\'m trying to

8条回答
  •  鱼传尺愫
    2020-12-12 13:23

    I ran into a similar need. I wanted to default to a 1X1 transparent pixel if an img url was null or returned an error (404 etc).

    import { Directive, Input } from '@angular/core';
    
    @Directive({
        selector: 'img[src]',
        host: {
            '[src]': 'checkPath(src)',
            '(error)': 'onError()'
        }
    })
    export class DefaultImage { 
        @Input() src: string;
        public defaultImg: string = '{YOUR_DEFAULT_IMG}';
        public onError() {
            this.src = this.defaultImg;
        }
        public checkPath(src) {
            return src ? src : this.defaultImg;
        }
    }
    

    Markup

    
    

提交回复
热议问题