Skip to content

Instantly share code, notes, and snippets.

@bojidaryovchev
Created January 12, 2023 21:15
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 bojidaryovchev/0a9c8724b77b3f5d42174e0e3b852101 to your computer and use it in GitHub Desktop.
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!
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