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?
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
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();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With