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?

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

Comments

6

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();
    ...
  }

2 Comments

MDN states: Assigning a value to effectAllowed in events other than dragstart has no effect.
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: jsfiddle.net/stevendwood/3sAYn/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.