Created
June 15, 2021 16:38
-
-
Save owrrpon/194ab3daee6d5f43873ddc901c9df8fd to your computer and use it in GitHub Desktop.
Drag and drop directive
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, EventEmitter, HostBinding, HostListener, Output } from '@angular/core'; | |
@Directive({ | |
selector: '[dragAndDrop]' | |
}) | |
export class DragAndDropDirective { | |
@Output() onFileDropped = new EventEmitter<any>(); | |
@HostBinding('style.opacity') private workspace_opacity = '1'; | |
// Dragover listener, when files are dragged over our host element | |
@HostListener('dragover', ['$event']) onDragOver(event: DragEvent) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
this.workspace_opacity = '0.5'; | |
} | |
// Dragleave listener, when files are dragged away from our host element | |
@HostListener('dragleave', ['$event']) public onDragLeave(event: DragEvent) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
this.workspace_opacity = '1'; | |
} | |
//Drop listener, when files are dropped on our host element | |
@HostListener('drop', ['$event']) public ondrop(event: DragEvent) { | |
event.preventDefault(); | |
event.stopPropagation(); | |
this.workspace_opacity = '1'; | |
let files = event.dataTransfer!.files; | |
if (files.length > 0) { | |
this.onFileDropped.emit(files) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment