How to get files from angular 2 onDrop event?

Vladimir picture Vladimir · Mar 23, 2017 · Viewed 18.5k times · Source

I tried like this but onDrop method don't return image files when I drop to it...

onDragStart(event, data: any) {
  event.dataTransfer.setData('data', data);
}
onDrop(event, data: any) {
  let dataTransfer = event.dataTransfer.getData('data');
  event.preventDefault();
}
allowDrop(event) {
  event.preventDefault();
}
<div (drop)="onDrop($event, dropData)" (dragover)="allowDrop($event)"></div>
<div (dragstart)="onDragStart($event, dragData)"></div>

Any solution for this?

Answer

maryl picture maryl · May 27, 2017

The event onDrop event fires only when onDragOver has preventDefault() and stopPropagation() methods run on event.

HTML

<div
    (drop)="onDrop($event)"
    (dragover)="onDragOver($event)"
>
    Drop target
</div>

DropComponent.ts

export class DropComponent {
    onDrop(event) {
        event.preventDefault();
    }
    onDragOver(event) {
        event.stopPropagation();
        event.preventDefault();
    }
}

UPDATE

This is required because by default the browser prevents anything from happening while dropping onto the HTML element. See more at MDN - Defining a valid drop zone