Issue
This Content is from Stack Overflow. Question asked by janaka ravindra
I have created a image inside the Div element.Then I have set the cdkdrag for img element. I only wanted to move image not div that is the reason I put cdkdrag for image tag.
But now the problem is If I go to change the Width and height of the .cdk-drag-preview class I can see image is small when dragging but when I move that image mouse pointer is not on the image it is beside the image. why is that happen how to fix that problem
.cdk-drag-preview {
width: 50px !important;
height: 50px !important;
}
Here is my jsFiddle : enter link description here
Solution
you can store in a variable the offset when mousedown and use cdkDragMoved in the way
offset:any=null
setStyle(event: MouseEvent) {
const rect = (event.target as HTMLElement).getBoundingClientRect();
this.offset={x:event.offsetX*50/rect.width,y:event.offsetY*50/rect.height };
}
public onDragMove(event: CdkDragMove<any>): void {
const el=(document.getElementsByClassName('cdk-drag-preview')[0])as any
const xPos = event.pointerPosition.x - this.offset.x;
const yPos = event.pointerPosition.y - this.offset.y;
el.style.transform = `translate3d(${xPos}px, ${yPos}px, 0)`;
}
the .html
<div class="dragItem" >
<img cdkDrag src="..."
(mousedown)="setStyle($event)"
(cdkDragMoved)="onDragMove($event)"
/>
</div>
NOTE: See that I remove de cdkDrag from outer div
This Question was asked in StackOverflow by janaka ravindra and Answered by Eliseo It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.