2019-10-25 13:04:21 +09:00
|
|
|
import {
|
|
|
|
Directive,
|
|
|
|
ElementRef,
|
|
|
|
EventEmitter,
|
|
|
|
Output,
|
|
|
|
Input,
|
|
|
|
AfterViewInit,
|
|
|
|
OnInit,
|
|
|
|
HostListener
|
|
|
|
} from '@angular/core';
|
|
|
|
|
|
|
|
import { NGXLogger } from 'ngx-logger';
|
|
|
|
|
|
|
|
@Directive({
|
2019-11-05 13:45:30 +09:00
|
|
|
selector: 'img[ucapImage]'
|
2019-10-25 13:04:21 +09:00
|
|
|
})
|
|
|
|
export class ImageDirective implements OnInit, AfterViewInit {
|
|
|
|
@Input()
|
|
|
|
base: string;
|
|
|
|
|
|
|
|
@Input()
|
|
|
|
path: string;
|
|
|
|
|
|
|
|
@Input()
|
|
|
|
validation = true;
|
|
|
|
|
|
|
|
@Input()
|
|
|
|
default: string;
|
|
|
|
|
|
|
|
@Output()
|
|
|
|
loaded = new EventEmitter<string>();
|
|
|
|
|
|
|
|
imageSrc: string;
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
private elementRef: ElementRef<HTMLImageElement>,
|
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|