8

I have a page (in Angular 4) where there is a drag and drop component (ng2-filedrop).The drag drop is working fine but when I drag a file and drop it in the page other that the drag and drop component, it opens the file in that page.

Is there any way to disable to file drop elsewhere or is it possible to atleast open the file in a separate browser tab?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Abx
  • 2,852
  • 4
  • 30
  • 50

2 Answers2

8

You can do that by overriding the dragover and drop event of the global window object that calls preventDefault() to prevent default drag&drop behavior of browser.

Add below code snippet to ngOnInit() method of your app.component.ts:

ngOnInit(): void {
  window.addEventListener("dragover", e => {
    e && e.preventDefault();
  }, false);
  window.addEventListener("drop", e => {
    e && e.preventDefault();
  }, false);
}

This is not my own answer, you can see the original answer and more discussions at Prevent browser from loading a drag-and-dropped file

Hoang Duc Nguyen
  • 389
  • 4
  • 13
5

The following is really similar to Hoang Duc Nguyen's Answer
The dropEffect shows the red crossed Cursor on Hover.

ngOnInit(): void {
        window.addEventListener("dragover", e => {
            e && e.preventDefault();
            e.dataTransfer.effectAllowed = "none";
            e.dataTransfer.dropEffect = "none";
        }, false);
        window.addEventListener("drop", e => {
            e && e.preventDefault();
            e.dataTransfer.effectAllowed = "none";
            e.dataTransfer.dropEffect = "none";
        }, false);
    }

Within the Component use the following.
If you want to differenciate between Files dropped from the User or Drop Events within the Page you could check the types.

@HostListener("dragover", ["$event"])
  onDragOver(ev: DragEvent) {
    if (ev.dataTransfer.types.includes("Files"))
      return;
    ev.preventDefault();
    ev.stopPropagation();
    ...
  }
JIT Solution
  • 693
  • 11
  • 14
  • MDN states: Assigning a value to effectAllowed in events other than dragstart has no effect. – Michal.S Aug 17 '21 at 16:15
  • I've seen it, but im pretty sure it had an effect. Correct me if I am wrong, but the following jsfiddle example uses the effectAllowed inside the dragover: http://jsfiddle.net/stevendwood/3sAYn/2/ – JIT Solution Aug 17 '21 at 17:15