简体   繁体   中英

Drag event not firing with angular 2

I have a canvas and I want users to be able to drag graphic elements around it. Thus, I don't want the canvas itself to drag, but I want to handle dragstart, drag, and drop events when the mouse does those things.

I'm using Angular 2, so I have:

<!-- editor.component.html -->
<div #rendererContainer
  draggable="true"
  (dragstart)="onDragStart($event)"
  (drag)="onDrag($event)" 
  (dragover)="onDrag($event)" 
  (drop)="onDragEnd($event)"
  (dragend)="onDragEnd($event)"> 
</div>

Then in editor.component.ts:

onDragStart(event) {
  console.log(`starting`);
  event.preventDefault();
}

onDrag(event) {
  console.log('dragging');
  event.preventDefault();
}

onDragEnd(event) {
  console.log('drag end');
  event.preventDefault();
}

When I try dragging something, I get starting printed in the console, but that's it. How do I get the other drag events to fire? Do I have to roll my own dragging from mousedown/move/up events?

Stand-alone example on stackblitz . I want "dragging" the div around to fire dragstart/drag/drop events, but it only fires the starting one.

You do not have to use event.preventDefault() . This is only necessary if you want to use pure JS.

Try this Stackblitz: https://stackblitz.com/edit/angular-x7umar

Also refer to the MDN implementation guide to choose the right events for your purposes: https://developer.mozilla.org/en-US/docs/Web/Events/drag

Further steps

If you want to modify the dragged element, simply implement some CSS adjustments inside your dragstart and dragend handler of the event.target :

onDragStart(event: DragEvent) {
  console.log(`starting`, event);
  // Hide dragged element
  event.target.style.opacity = 0;
}

onDragEnd(event: DragEvent) {
  console.log('drag end', event);
  // Show dragged element again
  event.target.style.opacity = 1;
}

With event.target you have the complete manipulable DOM element of the dragged element.

try with

(dragover)="onDragOver($event)"
(dragleave)="onDragLeave($event)"

Component

onDragOver(event) {
    // do something
    event.preventDefault();
}
onDragLeave(event) {
    // do something
    event.preventDefault();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM