Super easy solution which ChatGPT gave to me and i tested it (it uses tailwindcss classes):
To implement dragging, you can use the "Draggable" directive from the "@angular/cdk/drag-drop" package.
Install the package:
npm install @angular/cdk
Import the Draggable directive and DragDropModule into the module where you will use the markup (app.module.ts in base case):
import { DragDropModule } from '@angular/cdk/drag-drop';
@NgModule({
imports: [
...
DragDropModule
],
...
})
export class YourModule { }
- Add the Draggable directive to your div:
<div id="parent" class="border h-32 w-56 relative">
<div cdkDrag class="border absolute top-0 left-0 w-24 h-16 cursor-move"></div>
</div>
With this directive, you can drag elements within their parent container.
If you want the div to move only horizontally or vertically, you can add the parameter cdkDragFreeDrag="false"
.
Another useful parameter is cdkDragBoundary
, which allows you to define the rectangle in which the element can be moved.
<div cdkDrag class="border absolute top-0 left-0 w-24 h-16 cursor-move"
[cdkDragBoundary]="boundary"></div>
And in the component, define the boundary
property:
import { Component } from '@angular/core';
@Component({
...
})
export class YourComponent {
boundary = '#parent'; // a selector of the parent container
}
Now the div will move only within its parent container, and its movement will be limited by its boundaries.