Created
August 9, 2018 10:41
-
-
Save sankarseran/deb5348a5b89e9d0c13a8ea6e80712be to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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