unicorn-components
Version:
<a target="_blank" href="https://getunicorn.io"><img src="https://bitbucket-assetroot.s3.amazonaws.com/c/photos/2017/Jul/07/2615006260-5-nitsnetsstudios-ondemand-UNI_avatar.png" align="left"></a>
76 lines (65 loc) • 2.44 kB
text/typescript
import { Component, ElementRef, EventEmitter, HostBinding, Input, OnChanges, Output, ViewChild } from '@angular/core';
import { UniInputBaseComponent } from '../../base/input-base/input-base.component';
export class UniImagePickerComponent extends UniInputBaseComponent implements OnChanges {
componentClass = true;
inputFile: ElementRef;
width = 300;
height = 150;
imageWidth = this.width;
imageHeight = this.height;
imageData = null;
imageDataChange = new EventEmitter();
dragging = false;
ngOnChanges(changes) {
if (!this.imageWidth && (changes.width || changes.imageWidth)) {
this.imageWidth = this.width;
}
if (!this.imageHeight && (changes.height || changes.imageHeight)) {
this.imageHeight = this.width;
}
if (changes.model) {
if (this.model && this.model instanceof Blob) {
const reader = new FileReader();
reader.readAsDataURL(this.model);
reader.onload = (e: any) => {
this.imageData = e.target.result;
this.imageDataChange.emit(this.imageData);
};
} else {
this.imageData = null;
if (this.inputFile) { this.inputFile.nativeElement.value = null; }
}
}
}
onImagePicked(event) {
if (!event.target.files || !event.target.files.length) { return false; }
this.modelChange.emit(event.target.files[0]);
}
onDragEnter(event) {
this.dragging = true;
}
onDragOver(event) {
event.dataTransfer.dropEffect = 'copy';
event.preventDefault();
}
onDragLeave(event) {
this.dragging = false;
}
onDrop(event) {
this.dragging = false;
if (!event.dataTransfer.files || !event.dataTransfer.files.length) { return false; }
this.modelChange.emit(event.dataTransfer.files[0]);
event.preventDefault();
}
clear() {
this.modelChange.emit(null);
this.imageDataChange.emit('');
}
}