import { Directive, ElementRef, EventEmitter, Output, Input, AfterViewInit, OnInit, HostListener } from '@angular/core'; import { NGXLogger } from 'ngx-logger'; @Directive({ selector: 'img[ucapUiImage]' }) export class ImageDirective implements OnInit, AfterViewInit { @Input() base: string; @Input() path: string; @Input() validation = true; @Input() default: string; @Output() loaded = new EventEmitter(); imageSrc: string; constructor( private elementRef: ElementRef, private logger: NGXLogger ) {} ngOnInit(): void { if (this.validation) { if ( !this.base || '' === this.base.trim() || !this.path || '' === this.path.trim() ) { this.imageSrc = this.default; } } } ngAfterViewInit(): void { if (this.imageSrc === this.default) { this.elementRef.nativeElement.src = this.default; this.loaded.emit(this.elementRef.nativeElement.src); } else { this.elementRef.nativeElement.src = this.default; const imageUrl = `${this.base}${this.path}`; const image = new Image(); image.onload = () => { if ('naturalHeight' in image) { if (image.naturalHeight + image.naturalWidth === 0) { image.onerror('naturalHeight'); return; } } if (image.width + image.height === 0) { image.onerror('width'); return; } this.elementRef.nativeElement.src = image.src; this.loaded.emit(this.elementRef.nativeElement.src); }; image.onerror = () => { this.elementRef.nativeElement.src = this.default; this.loaded.emit(this.elementRef.nativeElement.src); }; image.src = imageUrl; } } }