Skip to main content

Angular Material Drag And Drop UI Component(Part-1)


Angular Material Drag And Drop CDK provides a set of rich functionalities like as below:
  • Able to apply to drag functionality on any HTML elements with free motion over a page
  • Sorting list of HTML rendered items.
  • Custom drag handlers
  • Custom drag place holders
  • Limit the area to drag for an item.
This article is a series of parts where we going to discuss and understand all the features provided by drag and drop CDK.

Create An Angular Sample Application:

To understand step by step implementation of drag and drop functionalities, let's create a sample angular application.
Command to create angular application:

ng new your-project-name
Command to install angular material package:

ng add @angular/material

Import DragDropModule:

DragDropModule is loaded from '@angular/cdk/drag-drop' package. Now we need to import this DragDropModule on to the NgModule of the app module to get all features of it.
src/app/app.module.ts:
import { DragDropModule } from '@angular/cdk/drag-drop';

@NgModule({
  imports: [DragDropModule]
})
export class AppModule {}
// code hidden due to display purpose

cdkDrag Directive:

Adding cdkDrag Directive on an HTML element will get the ability to drag and drop.

Simple Example On Drag And Drop With cdkDrag Directive:

Let's create a simple example on drag and drop with cdkDrag directive as follows.
src/app/cdkDragSample/cdk.drag.sample.component.ts:
import { Component } from '@angular/core';

@Component({
    selector:'cdk-drag-sample',
    templateUrl:'cdk.drag.sample.component.html',
    styleUrls:['cdk.drag.sample.component.css']
})
export class CdkDragSampleComponent {

}
Now add the following CSS styles to the component styles file
src/app/cdkDragSample/cdk.drag.sample.component.css:
.my-box {
    width: 200px;
    height: 200px;
    border: solid 1px #ccc;
    color: rgba(0, 0, 0, 0.87);
    cursor: move;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    background: #fff;
    border-radius: 4px;
    position: relative;
    z-index: 1;
    transition: box-shadow 200ms cubic-bezier(0, 0, 0.2, 1);
    box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2),
                0 2px 2px 0 rgba(0, 0, 0, 0.14),
                0 1px 5px 0 rgba(0, 0, 0, 0.12);
  }
  
  .my-box:active {
    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);
  }
Now let add HTML element with cdkDrag directive on it.
src/app/cdkDragSample/cdk.drag.sample.component.html:
<div class="my-box" cdkDrag>
    Hey you can drag me!
    Because i use cdKDrag directive
</div>
#L1 at this line cdkDrag directive decorated on 'div' element. Now this 'div' element has the capability of drag and drops on any place on a page.

Now let's run the application and output shows as below.

cdkDropList Directive:

cdkDropList directive applied over the group of Html elements each is decorated with cdkDrag directive. By using the cdkDropList directive we can do list elements ordering within its range. So the cdkDropList directive will act as a parent to the group of cdkDrag directives.

Drag And Drop List Of Elements By Using cdkDropList Directive:

Let's start creating a sample application for the Html element list sorting using the cdkDropList Directive.
src/app/listOrder/list.order.component.ts:
import { Component } from '@angular/core';

@Component({
    selector:'list-order',
    templateUrl:'list.order.component.html',
    styleUrls:['list.order.component.css']
})
export class ListOrderComponent {
    players = [
       'Rohit Sharma',
       'Shikar Dhawan',
       'Virat Kohli',
       'Ms Dhoni',
       'Ambati Rayudu',
       'Hardik Pandya'
    ];
}
#L9-L16 at these lines array of data that is going to be rendered as a list.

Let's add the following styles in the component styles file.
src/app/listOrder/list.order.component.css:
.my-list {
    width: 500px;
    max-width: 100%;
    border: solid 1px #ccc;
    min-height: 60px;
    display: block;
    background: white;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .my-box {
    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);
  }
  
  .my-box:last-child {
    border: none;
  }
  
  .my-list.cdk-drop-list-dragging .my-box:not(.cdk-drag-placeholder) {
    transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
  }
Let's add the component Html as follows.
src/app/listOrder/list.order.component.html:
<div class="my-list" cdkDropList>
    <div class="my-box" *ngFor="let player of players" cdkDrag>
        {{player}}
    </div>
</div>
  • #L1 at this line parent div element decorated with cdkDropList directive.
  • #L2 at this line div element decorated with cdkDrag directive makes this element as draggable. Since it, parent element decorated with cdKDropList all the draggable elements inside of it will be sorted within its range. "players" is a component array of data property that will get render by looping the data.
Now, reference this list order component HTML selector on to the app component HTML as below.
src/app/app.component.html:
<list-order></list-order>
Now import the list order component to the app module as below.
import { ListOrderComponent } from './listOrder/list.order.component';

@NgModule({
  declarations: [
    ListOrderComponent,
  ]
})
export class AppModule {}
// code hidden for display purpose
Now run the application and output shows as below.

Above Example Result:

We can observe in above example we are able to drag and drop the element with in the cdkDropList range. But after drag and drop item, we can observe that items refreshed back to original positions, means the result looks same as on pageload. It looks like drog and drop not working. But what happens actually is html element gets drag and dropped successfully, but the data binded(players component property) will not get sorted automatically on using cdkDropList dirctive.

so to fix the result of this example we need to use 'cdkDropListDropped' event.

cdkDropListDropped Event:

cdkDropListDropped event used to update the component data on dragging and dropping of an element.

Let's add a method that will be invoked by the cdkDrpListDropped event as follows.
src/app/listOrder/list.order.component.ts:(update file)
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
@Component({
    selector:'list-order',
    templateUrl:'list.order.component.html',
    styleUrls:['list.order.component.css']
})
export class ListOrderComponent {
    drop(event:CdkDragDrop<string[]>){
        moveItemInArray(this.players, event.previousIndex, event.currentIndex);
    }
}
// code hidden for display purpose
  • #L1 at this line CdkDragDrop instance and moveItemInArry method are get imported from '@angular/cd/drag-drop' package
  • CdkDragDrop is an instance of the generic type where can capture event data of the cdkDropListDroped event.
  • moveItemInArray is a method, that takes our array of data as input it will sort the data as per drag and drop element indexing.
  • #L8-L10 at these lines 'drop' a component method is created and this method will be registered to listen for the cdkDropListDropped event.
  • #L9 at this line moveItemInArray method gets called by inputting our 'players' property which of type array of objects and then index values to as input values to sort the 'players' property data based on drag and drop position.
Let's register Html with cdkDropListDropped event as below
src/app/listOrder/list.order.component.html:(update file)
<div class="my-list" cdkDropList (cdkDropListDropped)="drop($event)">
    <div class="my-box" *ngFor="let player of players" cdkDrag>
        {{player}}
    </div>
</div>
#L1 at this line 'cdkDropListDropped' event registered with 'drop'(method in component)

Now run the application and output shows as below.
After dragging and dropping output shows as below
Now we observe data get successfully updated on dragging and dropping of an element.

Sample Example Using Data Object Array:

Previously we used data objects as an array of string values, now we going to replace it with an array of object models.

src/app/listOrder/list.order.component.ts:(update file)
import { Component } from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';

@Component({
    selector:'list-order',
    templateUrl:'list.order.component.html',
    styleUrls:['list.order.component.css']
})
export class ListOrderComponent {
    players:any[]=[{
        id: 1,
        Name:"Rohit Sharma",
        Position:1 
    },{
        id:2,
        Name:"Virat Kohli",
        Position:2
    },{
        id:3,
        Name:"MS Dhoni",
        Position:3
    },{
        id:4,
        Name:"Shikar Dhawan",
        Position:4
    },{
        id:5,
        Name:"Ambati Rayudu",
        Position:5
    }]

    drop(event:CdkDragDrop<string[]>){
        moveItemInArray(this.players, event.previousIndex, event.currentIndex);
        this.players.forEach((value, index) => {
            value.Position = (index + 1);
        });
    }
}
  • #L10-L30 at these lines array of players object initialized(previously we used an array of string values).
  • #L33 at this line moveItemInArray sorts the object based on drag and drop indexes.
  • #L34-L36 at these lines since moveItemInArray method sorts "players" array object, after that we can update the correct 'Position' value using its index.
Let's update the Html code as follows.
src/app/listOrder/list.order.component.html:(update file)
<div class="my-list" cdkDropList (cdkDropListDropped)="drop($event)">
    <div class="my-box" *ngFor="let player of players" cdkDrag>
        Name: {{player.Name}},   Position:{{player.Position}}
    </div>
</div>
Now run the application and output shows as below.
After drag and drop, the output shows as below.

Wrapping Up:

Hopefully, I think this article delivered some useful information on the Drag and Drop Angular Material CDK. I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:


Follow Me:

Comments

Popular posts from this blog

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

.Net5 Web API Managing Files Using Azure Blob Storage

In this article, we are going to understand the different file operations like uploading, reading, downloading, and deleting in .Net5 Web API application using Azure Blob Storage. Azure Blob Storage: Azure blob storage is Microsoft cloud storage. Blob storage can store a massive amount of file data as unstructured data. The unstructured data means not belong to any specific type, which means text or binary data. So something like images or pdf or videos to store in the cloud, then the most recommended is to use the blob store. The key component to creating azure blob storage resource: Storage Account:- A Storage account gives a unique namespace in Azure for all the data we will save. Every object that we store in Azure Storage has an address. The address is nothing but the unique name of our Storage Account name. The combination of the account name and the Azure Storage blob endpoint forms the base address for each object in our Storage account. For example, if our Storage Account is n

.Net5 Web API Redis Cache Using StackExchange.Redis.Extensions.AspNetCore Library

In this article, we are going to explore the integration of Redis cache in .Net5 Web API application using the 'StackExchange.Redis.Exntensions' library. Note:- Microsoft has introduced an 'IDistributedCache' interface in dotnet core which supports different cache stores like In-Memory, Redis, NCache, etc. It is simple and easy to work with  'IDistributedCache', for the Redis store with limited features but if we want more features of the Redis store we can choose to use 'StackExchange.Redis.Extensions'.  Click here for Redis Cache Integration Using IDistributedCache Interface . Overview On StackExchange.Redis.Extnesions Library: The 'StackExchange.Redis.Extension' library extended from the main library 'StackExchange.Redis'. Some of the key features of this library like: Default serialization and deserialization. Easy to save and fetch complex objects. Search key. Multiple Database Access Setup Redis Docker Instance: For this sampl

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

NestJS File Upload

In this article, we are going to understand the steps to create a file uploading endpoint in the NestJS application. Key Features In NestJS File Upload: Let us know some key features of NestJS file upload before implementing a sample application. FileInterceptor: The 'FileInterceptor' will be decorated on top of the file upload endpoint. This interceptor will read single file data from the form posted to the endpoint. export declare function FilesInterceptor(fieldName: string, localOptions?: MulterOptions): Type<NestInterceptor>; Here we can observe the 'fieldName' first input parameter this value should be a match with our 'name' attribute value on the form file input field. So our interceptor read our files that are attached to the file input field. Another input parameter of 'MulterOptions' that provides configuration like file destination path, customizing file name, etc. FilesInterceptor: The 'FilesInterceptor' will be decorated on t

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload: The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.  Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.  Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.  If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application. Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.   Check the link to use the Visual Studio Code for .NET Core Application . IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files f

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items. The main building block of ion-picker as follows: PickerController PickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker. Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger&quo

.Net Core HttpClient JSON Extension Methods Using System.Net.Http.Json Package

.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call. System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below. GetFromJsonAsync PostAsJsonAsync PutAsJsonAsync ReadFromJsonAsync In this article, we understand System.Net.Http.Json package by implementing the HttpClient samples by with and without JSON extension methods and compare them. Create A .Net Core Web API Sample Application: Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or  Visual Studio Code . Create A Typed Client: In .Net Core using the Http