I'm currently working on a web application that allows users to create their own identity cards.
For this project, I am incorporating the ng-drag-drop
library from
https://www.npmjs.com/package/ng-drag-drop
.
The main goal is to obtain the coordinates of a div
box within a larger div
container.
In specific, I am looking for the (x,y)
position relative to the outer div
.
Here are the key objectives:
- Position the inner div at a specified location within the outer div.
- Allow draggable functionality and retrieve updated coordinates.
Issue: When I programmatically reposition the box and then move it around, the x,y values turn out to be negative –
HTML:
<div class="card-boundary" #boundary>
<img width="1039" height="673" [ngStyle]="bgStyle" />
<div cdkDragLockAxis="elem.dragLock" (cdkDragEnded)="dragEnd($event)" (cdkDragStarted)="onElemClick(elem,$event)" cdkDragBoundary=".card-boundary" cdkDrag *ngFor="let elem of elemList" [ngClass]="{'example-box-selected':(selectedElem && elem.field == selectedElem.field)}"
(click)="onElemClick(elem,$event)" class="example-box" style="text-align: start" [ngStyle]="elem" #item>
{{elem.sample}}
</div>
</div>
Typescript:
dragEnd(event: CdkDragEnd) {
const transform = event.source.element.nativeElement.style.transform;
let regex = /translate3d\(\s?(?<x>[-]?\d*)px,\s?(?<y>[-]?\d*)px,\s?(?<z>[-]?\d*)px\)/;
var values = regex.exec(transform);
this.selectedElem.startX = +values[1];
this.selectedElem.startY = +values[2];
}
CSS:
.card-boundary {
width: 1039px;
height: 676px;
max-width: 100%;
position: relative;
background-color: #fff
}
.bg-boundary {
width: 1039px;
height: 676px;
max-width: 100%;
}
.example-box {
cursor: move;
position: relative;
z-index: 1;
}
.example-box-selected {
cursor: move;
background: #eee;
position: relative;
z-index: 1;
}