Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent browser from loading a drag-and-dropped file in Angular

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?

like image 801
Abx Avatar asked Oct 18 '17 11:10

Abx


2 Answers

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

like image 96
Hoang Duc Nguyen Avatar answered Oct 13 '22 20:10

Hoang Duc Nguyen


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();
    ...
  }
like image 38
JIT Solution Avatar answered Oct 13 '22 20:10

JIT Solution