Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using mousedown HostListener to move elements around (Drag & Drop)

We need to create a drag and drop directive. Using drag and drop events won't work for SVG elements, thus, we need to go for standard mousedown, mousemove and mouseup events. I saw a few examples in JavaScript, but somehow I don't get it working with Angular.

The mousemove works solong the draggable element is not selected.

How can I pick the element and drag it around with HostListener mousemove?

I created a StackBlitz so you can see what I've done. If I drag the element and open the console, you'll see that the mousemove event won't be fired.

what am I missing?

like image 340
DAG Avatar asked Sep 03 '25 04:09

DAG


1 Answers

I supported an easy way to solve because of event stuck.

Apparently, out first goal is stop the event that is preventdefault . In your hostListener , it supported in your event.

event.preventDefault();

In addition, it got more easy way is return false and it would be interrupt.

@HostListener('document:mousedown', ['$event'])
onMouseDown(event) {
  // we make sure only draggables on the document elements are selected
  if (event.target.getAttribute('draggable')) {
    console.log('mousedown');

    this.currentX = event.clientX;
    this.currentY = event.clientY;
    this.selectedElement = event.target;
    // ##### add this code.
    event.preventDefault();    // choose one
    // ##### or add this code.
    return false;    // choose one
  }
}
like image 107
Rach Chen Avatar answered Sep 06 '25 05:09

Rach Chen