Angular 16 Drag and Drop Tutorial with Example

Last Updated on by in Angular

Angular Drag and Drop tutorial with example, is going to be discussed in this blog.

I’ll teach you how to achieve Angular drag and drop functionality using Angular Material 16 in no time. Creating drag and drop with Angular is as easy as stealing candy from a baby.

It is clear from this that, we have to install and configure the basic Angular app along with Angular Material UI library.

Angular Material is a well-known UI library, and it offers a wide array of pre-developed UI components.

Using these components, you can create flexible, robust, and cross-browser compatible user-interfaces in minutes.

If we talk about UI and UX design consistency in Angular Material, so it’s top notch.

Once we are done with setting up our Angular app, then we will move on further and learn to use the DragDropModule in the Angular Material library.

So without further ado, let us begin creating Angular Drag and Drop tutorial from the beginning.

Angular Material 16 Drag and Drop Example

  • Step 1: Set up Angular Project
  • Step 2: Set Up Angular Material
  • Step 3: Create Angular Material Drag and Drop Reordering List
  • Step 4: Transferring Items Within the Lists with cdkDropList
  • Step 5: View App on Browser

Set up Angular project with Angular Material Library

Run command to set up a basic Angular project:

ng new angular-drag-drop

Answer angular CLI questions:

Would you like to add Angular routing?
Select y and Hit Enter.

Which stylesheet format would you like to use? (Use arrow keys)
Choose SCSS and hit Enter

Then, step inside the project folder:

cd angular-drag-drop

No Property Access From Index Signature

To resolve error:

Property ‘xxxName’ comes from an index signature, so it must be accessed with [‘xxxName’]

This setting makes sure profound consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set noPropertyAccessFromIndexSignature property to false under compilerOptions in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
}

Install Angular Material library:

ng add @angular/material

Choose Angular Material Pre-built theme:

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink

❯ Indigo/Pink        [ Preview: https://material.angular.io?theme=indigo-pink ] 
  Deep Purple/Amber  [ Preview: https://material.angular.io?theme=deeppurple-amber ] 
  Pink/Blue Grey     [ Preview: https://material.angular.io?theme=pink-bluegrey ] 
  Purple/Green       [ Preview: https://material.angular.io?theme=purple-green ]

Choose Hammer.js (Gesture recognition support) and Angular browser animation service.

# Set up HammerJS for gesture recognition? (Y/n) = Y
# ? Set up browser animations for Angular Material? (Y/n) = Y

Import Angular Material services in app module file.

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

@NgModule({
  declarations: [...],
  imports: [
    BrowserAnimationsModule
  ],
  providers: [...],
  bootstrap: [...],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

Configure Angular Material CDK Drag and Drop in Angular

Now, we will configure Angular Material CDK Drag and Drop in Angular app. Follow the below process:

npm install @angular/cdk

Then, import the DragDropModule service in app.module.ts.

import { DragDropModule } from '@angular/cdk/drag-drop';

@NgModule({
  declarations: [...],
  imports: [
    DragDropModule
  ],
  providers: [...],
  bootstrap: [...],
  schemas: [...]
})

Understand CdkDropList

If we talk about CdkDropList service, its the container that holds the draggable elements, check out the CdkDropList selectors below.

[cdkDropList] cdk-drop-list

The Angular Drag and Drop Method

Angular offers the drop() method for dragging and dropping the items on container.

To know more about Angular Material drag and drop CDK read the documentation here.

Create Angular Material Drag and Drop Reordering List

Now we are into the most important part of our tutorial, here we will create a list, the items of this list can easily be dragged and dropped by the user. Add the given below code in app.component.html.

<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
  <div class="example-box" *ngFor="let movieName of Movies" cdkDrag>{{movieName}}</div>
</div>

Add the following CSS code to style our drag and drop block. Paste the code in app.component.scss file.

.wrapper{margin:25px auto;max-width:600px;text-align:center;padding:0 20px;}
.container{width:45%;margin:0 25px 25px 0;display:inline-block;vertical-align:top;}
.movie-list{width:80%;border:solid 1px #ccc;min-height:60px;display:inline-block;background:white;border-radius:4px;overflow:hidden;margin-top:25px;}
.movie-block{padding:20px 10px;border-bottom:solid 1px #ccc;color:rgba(0, 0, 0, 0.87);display:flex;flex-direction:row;align-items:center;justify-content:space-between;box-sizing:border-box;cursor:move;background:white;font-size:14px;}
.cdk-drag-preview{box-sizing:border-box;border-radius:4px;box-shadow:0 5px 5px -3px rgba(0, 0, 0, 0.2), 0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12);}
.cdk-drag-placeholder{opacity:0;}
.cdk-drag-animating{transition:transform 250ms cubic-bezier(0, 0, 0.2, 1);}
.movie-block:last-child{border:none;}
.movie-list.cdk-drop-list-dragging .movie-block:not(.cdk-drag-placeholder){transition:transform 250ms cubic-bezier(0, 0, 0.2, 1);}

Now, it’s time to import the CdkDragDrop and moveItemInArray service from ‘@angular/cdk/drag-drop’. These services will allow us to drag and drop items in a specific container.

Go to app.component.ts file and add the given below code in it.

import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  Movies = [
    'Blade Runner',
    'Cool Hand Luke',
    'Heat',
    'Juice',
    'The Far Side of the World',
    'Morituri',
    'Napoleon Dynamite',
    'Pulp Fiction'
  ];

  drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.Movies, event.previousIndex, event.currentIndex);
  }
}

Transferring Items Within the Lists with cdkDropList

Now, we are going to use cdkDropList directive to build the angular drag and drop functionality. We can drag and drop any item within the container.

Go inside app.component.ts and add the given below code.

import { Component } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

export class AppComponent {
  // Transfer Items Between Lists
  MoviesList = [
    'The Far Side of the World',
    'Morituri',
    'Napoleon Dynamite',
    'Pulp Fiction',
    'Blade Runner',
    'Cool Hand Luke',
    'Heat',
    'Juice'
  ];

  MoviesWatched = [
  ];

  onDrop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex);
    }
  }  
}

Go to app.component.html file and paste the below code.

<div class="container">
   <h2>Movies</h2>
   <div 
   cdkDropList 
   #moviesList="cdkDropList" 
   [cdkDropListData]="MoviesList"
   [cdkDropListConnectedTo]="[doneMovieList]" 
   class="movie-list" 
   (cdkDropListDropped)="onDrop($event)">
   <div class="movie-block" *ngFor="let moviesList of MoviesList" cdkDrag>{{moviesList}}</div>
</div>
</div>

<div class="container">
   <h2>Movies Watched</h2>
   <div 
   cdkDropList 
   #doneMovieList="cdkDropList" 
   [cdkDropListData]="MoviesWatched"
   [cdkDropListConnectedTo]="[moviesList]" 
   class="movie-list" 
   (cdkDropListDropped)="onDrop($event)">
   <div class="movie-block" *ngFor="let moviesWatched of MoviesWatched" cdkDrag>{{moviesWatched}}</div>
</div>
</div>

Run the following command to serve your app locally:

ng serve --open

Open a web browser and navigate to:

 http://localhost:4200/

Conclusion

Finally, we have completed Angular Drag and Drop tutorial with example blog.

We have barely scratch the surface in this tutorial, but it surely help us to understand the how to get started.

You can click on the button below to check out the Git repo of this project.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.