I've been working on implementing a photo uploader that requires the order of photos to be maintained. In order to achieve this, I have attempted to incorporate a drag and drop feature to swap their positions. However, I am encountering an issue where I am unable to drop images directly on top of each other. Instead, I am required to place them within the surrounding div element. Here is the snippet from component.html:
<div class="container">
<div class="row">
<div class="col-12">
<input type="file" multiple (change)="onSelectFile($event)" />
</div>
<div class="col-12">
<div
class="photos-container"
(dragover)="onDragOver($event)"
(drop)="onDrop($event)"
>
<div
*ngFor="let image of images; index as i"
class="photo"
[draggable]="true"
(dragstart)="onDragStart(i, $event)"
style="background-color: black;"
>
<img [src]="image" style="width: 200px; height: 200px;" />
</div>
</div>
</div>
</div>
</div>
The code for component.ts is:
onSelectFile(event: any) {
if (event.target.files.length > 0) {
this.files = event;
const files = Array.from(event.target.files);
files.forEach((file: any) => {
const reader = new FileReader();
reader.onload = (e: any) => {
this.images.push(e.target.result);
};
reader.readAsDataURL(file);
this.imageChangedEvnt = event;
});
}
}
onDragStart(index: any, event: any) {
event.dataTransfer.setData("index", index);
}
onDragOver(event: any) {
event.preventDefault();
}
onDrop(event: any) {
const index = event.dataTransfer.getData("index");
const newIndex = Array.from(event.currentTarget.children).indexOf(
event.target
);
if (newIndex >= 0) {
const photo = this.images.splice(index, 1)[0];
this.images.splice(newIndex, 0, photo);
}
}
Check out the live demo here: Demo
Despite trying the above code, I'm still facing issues with dropping images directly on top of each other. The swapping functionality only works when the images are placed within the surrounding div.