Movement Restriction
The DragTarget
directive allows you to move the element only within the boundaries of a specified container.
The following example demonstrates how to restrict the element movement within the container boundaries.
Setup
To implement the container restriction demonstrated above, you will need the following information:
- The initial
clientX
/clientY
—The client coordinates where the dragging begins (retrieved from theonDragStart
event). - The current
clientX
/clientY
—The client coordinates of the current positioning of the pointer (retrieved on eachonDrag
event).
Here is a step-by-step guide on how to achieve the same setup:
-
Set the
mode
property tomanual
in order to take full control over the drag and drop action. -
Handle the
onDragStart
event to get the initialclientX
andclientY
values and to get the current DragTarget HTML element.
public handleDragStart(ev: DragTargetDragStartEvent): void {
this.currDragTarget = e.dragTarget;
this.renderer.setStyle(this.currDragTarget, 'transition', 'none');
this.initialPosition = {
x: e.dragEvent.clientX,
y: e.dragEvent.clientY
};
}
- Handle the
onDrag
event to calculate the current position of the DragTarget and to apply the correspondingtransform
style to the element.
public handleDrag(ev: DragTargetDragEvent): void {
this.currentPosition = {
x: e.dragEvent.clientX - this.initialPosition.x,
y: e.dragEvent.clientY - this.initialPosition.y
};
const transformStyle = this.getTransform();
this.renderer.setStyle(this.currDragTarget, 'transform', transformStyle);
}
private getTransform(): string {
const parentRect = this.currDragTarget.parentElement.getBoundingClientRect();
const elRect = this.currDragTarget.getBoundingClientRect();
const xMax = (parentRect.width - elRect.width)/2;
const yMax = (parentRect.height - elRect.height)/2;
const updatedPosition = {x: 0, y: 0};
// the xMax/yMax value can either be a positive or a negative number depending on the dragging direction
if (this.currentPosition.x > 0) {
updatedPosition.x = Math.max(0, Math.min(this.currentPosition.x, xMax));
} else {
updatedPosition.x = Math.min(0, Math.max(this.currentPosition.x, -xMax));
}
if (this.currentPosition.y > 0) {
updatedPosition.y = Math.max(0, Math.min(this.currentPosition.y, yMax));
} else {
updatedPosition.y = Math.min(0, Math.max(this.currentPosition.y, -yMax));
}
return `translate(${updatedPosition.x}px, ${updatedPosition.y}px)`;
}
- Handle the
onRelease
event to remove thetransform
style and add/remove any other styling rules.
public handleRelease(): void {
this.btnText = 'Press Me!';
if (this.currDragTarget) {
this.renderer.removeStyle(this.currDragTarget, 'transform');
this.renderer.setStyle(this.currDragTarget, 'transition', this.dragTargetTransition);
}
}