Created
January 12, 2023 21:15
-
-
Save bojidaryovchev/0a9c8724b77b3f5d42174e0e3b852101 to your computer and use it in GitHub Desktop.
Angular Upload Container component - wrap anything inside, drag and drop a file on top and voila!
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 { Component, EventEmitter, HostBinding, HostListener, Input, Output } from '@angular/core'; | |
@Component({ | |
selector: 'upload-container', | |
template: '<ng-content></ng-content>', | |
}) | |
export class UploadContainerComponent { | |
@HostBinding('class.drop-area-active') @Input() dropAreaActive?: boolean; | |
@Output() dropAreaActiveChange = new EventEmitter<boolean>(); | |
@Output() filesChange = new EventEmitter<File[]>(); | |
@HostListener('dragenter') | |
onDragEnter(): void { | |
this.setDropAreaActive(true); | |
} | |
@HostListener('dragover', ['$event']) | |
onDragOver(event: DragEvent): void { | |
event.preventDefault(); | |
} | |
@HostListener('dragleave') | |
onDragLeave(): void { | |
this.setDropAreaActive(false); | |
} | |
@HostListener('drop', ['$event']) | |
onDrop(event: DragEvent): void { | |
event.preventDefault(); | |
this.setDropAreaActive(false); | |
if (!event.dataTransfer) { | |
return; | |
} | |
const dataTransferItems = Array.from(event.dataTransfer.items); | |
const files: File[] = []; | |
for (const dataTransferItem of dataTransferItems) { | |
const file = dataTransferItem.getAsFile(); | |
if (!file) { | |
continue; | |
} | |
files.push(file); | |
} | |
if (!files.length) { | |
return; | |
} | |
this.filesChange.emit(files); | |
} | |
private setDropAreaActive(dropAreaActive: boolean): void { | |
this.dropAreaActive = dropAreaActive; | |
this.dropAreaActiveChange.emit(dropAreaActive); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment