Skip to content

Instantly share code, notes, and snippets.

@sankarseran
Created August 9, 2018 10:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sankarseran/deb5348a5b89e9d0c13a8ea6e80712be to your computer and use it in GitHub Desktop.
Save sankarseran/deb5348a5b89e9d0c13a8ea6e80712be to your computer and use it in GitHub Desktop.
import { Directive, HostListener, HostBinding, EventEmitter, Output, Input } from '@angular/core';
@Directive({
selector: '[appDragAndDrop]'
})
export class DragAndDropDirective {
@Input() private allowed_extensions: Array<string> = [];
@Output() private filesChangeEmiter: EventEmitter<File[]> = new EventEmitter();
@Output() private filesInvalidEmiter: EventEmitter<File[]> = new EventEmitter();
@HostBinding('style.background') private background = '#eee';
constructor() { }
@HostListener('dragover', ['$event']) public onDragOver(evt) {
evt.preventDefault();
evt.stopPropagation();
this.background = '#999';
}
@HostListener('dragleave', ['$event']) public onDragLeave(evt) {
evt.preventDefault();
evt.stopPropagation();
this.background = '#eee';
}
@HostListener('drop', ['$event']) public onDrop(evt) {
evt.preventDefault();
evt.stopPropagation();
this.background = '#eee';
const files = evt.dataTransfer.files;
const valid_files: Array<File> = [];
const invalid_files: Array<File> = [];
if (files.length > 0) {
files.forEach((file) => {
const ext = file.name.split('.')[file.name.split('.').length - 1];
if (this.allowed_extensions.lastIndexOf(ext) !== -1) {
valid_files.push(file);
} else {
invalid_files.push(file);
}
});
this.filesChangeEmiter.emit(valid_files);
this.filesInvalidEmiter.emit(invalid_files);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment