This makes building interactive and intuitive UIs much easier with Angular's CDK drag-drop module. It abstracts some of the more complex tasks, like handling events and manipulating the DOM, which allows developers to easily incorporate drag-and-drop functionality with a hint from usability or functionality.
1. Install Angular CDK
Let's install the Angular CDK package to start:
npm install @angular/cdk
2. Import the DragDropModule
In your app module file, import the module:
import { DragDropModule } from '@angular/cdk/drag-drop';@NgModule({ imports: [DragDropModule],})export class AppModule {}
3. Define Drag-and-Drop in HTML
Use cdkDropList for the container and cdkDrag for draggable elements:
<div cdkDropList (cdkDropListDropped)="drop($event)"> <!-- Loop through items and make each one draggable --> <div *ngFor="let item of items" cdkDrag> {{ item }} </div></div>
4. Handle Drag-and-Drop Events in TypeScript
now add the logic to refresh the list order when an item is been dragged and dropped.
import { Component }from'@angular/core';import {moveItemInArrayCdkDragDrop} from'@angular/cdk/drag-drop';@Component({ selector : 'app-root', templateUrl: './app.component.html'})export class AppComponent{items = ['Item1', 'Item2', 'Item3']}; drop(event : CdkDragDrop <string[]>) { moveItemInArray(this.items, event.previousIndex, event.currentIndex); }}
5. Add Styling (Optional)
Improve UI with basic styles:
div[cdkDrag] { padding: 10px; margin: 5px; background-color: lightgray; cursor: grab;}div[cdkDropList] { min-height : 180px; /* Ensures the container maintains a minimum height */ border : 1px dashed #ccc; /* Adds a light gray dashed border for visibility */ padding : 15px; /* Provides inner spacing for better content layout */}
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our Angular Expertise.
Contact Us