New to Kendo UI for Angular? Start a free 30-day trial
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.
Change Theme
Theme
Loading ...
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 theonDragStartevent). - The current
clientX/clientY—The client coordinates of the current positioning of the pointer (retrieved on eachonDragevent).
Here is a step-by-step guide on how to achieve the same setup:
-
Set the
modeproperty tomanualin order to take full control over the drag and drop action. -
Handle the
onDragStartevent to get the initialclientXandclientYvalues and to get the current DragTarget HTML element.
ts
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
onDragevent to calculate the current position of the DragTarget and to apply the correspondingtransformstyle to the element.
ts
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
onReleaseevent to remove thetransformstyle and add/remove any other styling rules.
ts
public handleRelease(): void {
this.btnText = 'Press Me!';
if (this.currDragTarget) {
this.renderer.removeStyle(this.currDragTarget, 'transform');
this.renderer.setStyle(this.currDragTarget, 'transition', this.dragTargetTransition);
}
}