import { Component, OnInit, Input, ElementRef } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { take } from 'rxjs/operators'; import { NGXLogger } from 'ngx-logger'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import { ucapAnimations } from '../animations'; @Component({ selector: 'ucap-ui-imaage', template: ` `, styles: [], animations: ucapAnimations }) export class ImageComponent implements OnInit { @Input() base: string; @Input() path: string; @Input() validation = true; @Input() default: string; @Input() set style(style: string | object) { let mappedStyles = style as string; if (typeof style === 'object') { mappedStyles = Object.entries(style).reduce( (styleString, [propName, propValue]) => { propName = propName.replace( /([A-Z])/g, matches => `-${matches[0].toLowerCase()}` ); return `${styleString}${propName}:${propValue};`; }, '' ); this.baseStyle = this.domSanitizer.bypassSecurityTrustStyle(mappedStyles); } else if (typeof style === 'string') { this.baseStyle = this.domSanitizer.bypassSecurityTrustStyle(mappedStyles); } } @Input() set imageClass(classes: string) { if (classes && classes.length) { classes.split(' ').forEach((className: string) => { this.classList[className] = true; }); this.elementRef.nativeElement.className = ''; } } baseStyle: SafeStyle; imageSrc: string; classList: { [key: string]: boolean } = {}; constructor( private elementRef: ElementRef, private domSanitizer: DomSanitizer, private httpClient: HttpClient, private logger: NGXLogger ) { this.imageSrc = null; } ngOnInit() { if (this.validation) { if ( !this.base || '' === this.base.trim() || !this.path || '' === this.path.trim() ) { this.imageSrc = this.default; } } if (!this.imageSrc) { this.imageSrc = this.default; const imageUrl = `${this.base}${this.path}`; const image = new Image(); image.onload = () => { if ('naturalHeight' in this) { if (image.naturalHeight + image.naturalWidth === 0) { image.onerror('naturalHeight'); return; } } else if (image.width + image.height === 0) { image.onerror('width'); return; } this.imageSrc = image.src; }; image.onerror = () => { this.imageSrc = this.default; }; image.src = imageUrl; } } }