Angular Tutorials

Angular 13 Drag and Drop Tutorial with Example

Angular 13 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 11 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.

Step 1: 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 CSS and hit Enter

Then, go inside the project folder:

cd angular-drag-drop

In order to remove strict type warnings or errors make sure to set “strict”: false and "strictTemplates": false under compilerOptions and angularCompilerOptions properties in tsconfig.json file.

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

Step 2: 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.

Step 3: 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.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 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 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

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

22 hours ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

7 days ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago