How To Build an Angular App with Drag and Drop

How To Build an Angular App with Drag and Drop

More than 7.7K companies manage their projects and activities on tech grounds. React, Flutter, Vue.js and many other frameworks have launched, but Angular is still listed as the top front-end framework.

The availability of resources, tools, developers, and community support, web app developers and large enterprises love angular.

To make the developer's job hassle-free and effortless angular is composite with many libraries. You just need to set up the app and perform some import and export actions in a declarative manner. Here is the brief information on the drag and drop functionality to achieve in the angular app.

How to Implement Drag and Drop in Aangular?

Angular developers frequently use the drag-and-drop functionality to build the app efficiently. This blog will use a UI component library- Angular material. It has a wonderful suite of UI components that drive consistency and flexibility to apps with appealing UI/ UX design.

Before we jump on the drag-and-drop implementation, it is required to configure the angular app.

1. Initiate an Angular Project Running the Following Command:

ng new angular-drag-drop

Some Angular CLI questions will prompt on-screen to take the desired action:

Confirm Angular routing with yes and enter key

Select the stylesheet CSS, press enter, and navigate to the project folder.

Hit the following command:

cd angular-drag-drop

Next, launch the Angular Material Library

ng add @angular/material

Access the default theme of Angular Material

? 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]

To pull animation and gesture support to your application, access Hammer.js along with the Angular Browser animation Service.

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

It’s time to import angular material services. Access the app module file and paste this code:

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

2. Setup Angular Material CDK Drag & Drop

Let’s initiate the configuration for Angular Material CDK.

npm install @angular/cdk

Inside app.module.ts pull the capabilities of DragDropModule:

import { DragDropModule } from '@angular/cdk/drag-drop';
@NgModule({
  declarations: [...],
  imports: [
    DragDropModule
  ],
  providers: [...],
  bootstrap: [...],
  schemas: [...]
})

Introducing CdkDropList service and Angular Drag & Drop Method:

CdkDropList: it stores draggable elements as a container.

[cdkDropList] cdk-drop-list

You can drag and drop the items into the container through drop(). It’s a method introduced in the angular officially for developers' convenience.

3. Let's Create the Drag-and-Drop Reordering List.

Copy and paste this code to app.component.html.

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

To make it look more styled and interactive and clear apply some CSS. Keep this code in the CSS file app.component.css:

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

Navigate to @angular/cdk/drag-drop and import the CdkDragDrop and moveItemInArray services to manage the drag-and-drop accessibility for a specified container.

Put up the following code in the app.component.ts file:

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

4. Drop Items to the List Ssing cdkDropList

cdkDropList is a directive to launch the drag-and-drop accessibility for container items.

Navigate to the app.component.ts and paste the following stuff:

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

Inside the app.component.html writeup this

<di 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>

Here we are done with this drag-and-drop procedure.

Final Words

Angular Drag and Drop Module provides the utmost support to access different types of functionalities. You can easily launch interactive and intuitive UIs by importing and exporting action. Be it animation, gestures, lists, or anything you can move and lock the things as per your project requirement. We hope the blog post will be helpful to you to get your job done in no time quickly without any hassle.

Did you find this article valuable?

Support Quokka Labs' Blogs by becoming a sponsor. Any amount is appreciated!