Angular 8/9 Drag and Drop Tutorial with Example

By Digamber Rawat Last updated on
Angular 8/9 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 8 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 8 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 8/9 Drag and Drop Tutorial with Example

Have a look what we are going to create, click on the button to view the drag and drop demo:

Demo on Stackblitz

Step 1: Set up Angular project with Angular Material 8 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 CSS and hit Enter

Then, go inside the project folder:

cd angular-drag-drop

Install Angular Material 8 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]
})

Step 2: Configure Angular Material 8 CDK Drag and Drop in Angular App

Now, we will configure Angular Material 8 CDK Drag and Drop in Angular 8/9 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.

Step 3: Create Angular Material 8 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.ts.

<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.css 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.css']
})

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);
  }
}

Step 4: Transferring Items Within the Lists with cdkDropList

Now, we are going to use cdkDropList directive to build the angular 8/9 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.css']
})

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>

Conclusion

Finally, we have completed Angular 8/9 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.

GitHub Repo

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.