Reputation: 85
So I have this HTML:
<div cdkDrag>
<div id="container">
<div>
<button id="add-left">+</button>
</div>
<div id="cell">
<span class="cell-title">
title
</span>
<span class="cell-desc">
<p>desc</p>
</span>
</div>
<div>
<button id="add-right" (click)="getPosition()">+</button>
</div>
</div>
</div>
<div cdkDrag id="div2" style="width: 100px; height: 100px; top:250px; left:600px; background:#4527a0; position:absolute;"></div>
<svg style="width: 100vw; height: 100vh;"><line id="line1" stroke="lime" style="stroke-width:3.5"/></svg>
And this Typescript function:
getPosition() {
const line = document.getElementById('line1');
const div1 = document.getElementById('add-right').getBoundingClientRect();
const div2 = document.getElementById('div2').getBoundingClientRect();
line.setAttribute('x1', (div1.left + div1.width / 2).toString());
line.setAttribute('y1', (div1.top + div1.height / 2).toString());
line.setAttribute('x2', (div2.left + div2.width / 2).toString());
line.setAttribute('y2', (div2.top + div2.height / 2).toString());
}
The getPosition() function updates the svg lines coordinates to connect the box and the cell. The thing is, that I want to be able to move the cell and the box, and so the line along with it. How would I go about updating the line every time the boxes are moved?
Upvotes: 1
Views: 38
Reputation: 6529
Looking at the cdk docs, there's a cdkDragMoved
that is fired whenever the item is being dragged.
<div cdkDrag (cdkDragMoved)="getPosition()">
<div id="container">
<div>
<button id="add-left">+</button>
</div>
<div id="cell">
<span class="cell-title">
title
</span>
<span class="cell-desc">
<p>desc</p>
</span>
</div>
<div>
<button id="add-right" (click)="getPosition()">+</button>
</div>
</div>
</div>
The docs mention to use this with caution, but it seems to be fit for your use case.
Emits as the user is dragging the item. Use with caution, because this event will fire for every pixel that the user has dragged.
Upvotes: 1