Drag and Drop: New Feature of Angular7

Posted By Himanshu Agarwal | 31-Oct-2018

Angular 7 has come up with many new features, and one of the most important being Drag and Drop
The @angular/
cdk/drag-drop module provides you with a way to easily and declaratively create drag-and-drop interfaces
with support for free dragging, transferring items between lists, sorting within a list, touch devices, animations, 
previews, and placeholders, custom drag handles, in addition to horizontal lists and locking along an axis.
First of all, we need to import DragDropModule into the
NgModule wherever we want to use drag and drop features.
Then we need to add the cdkDrag directive to elements for making them draggable. Outside of cdkDropList element, draggable elements can move freely around the page.


import {DragDropModule} from '@angular/cdk/drag-drop';
Selector: [cdkDropList]

It has various properties and methods which could be looked over on the Angular official website.

Basic drag and drop example:

<div class="example-box" cdkDrag>

  Drag me around


With Drag and Drop we also have Reordering lists feature: 
Code Example: 

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

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

 * @title Drag&Drop sorting
  selector: 'cdk-drag-drop-sorting-example',
  templateUrl: 'cdk-drag-drop-sorting-example.html',
  styleUrls: ['cdk-drag-drop-sorting-example.css'],
export class CdkDragDropSortingExample {
  cars = [
    ' I - Mercedez',
    ' II - Audi',
    ' III - Toyota',
    ' IV - Maruti',
    ' V - BMW',
    ' VI - Hyundai',
    ' VII - Honda',
    ' VIII - TATA'

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

Adding cdkDropList around a set of cdkDrag elements groups the draggable into a reorderable collection.
Items will automatically rearrange as an element moves. 
And this will not be updating your data model; 
For updating the data model we need to listen to the cdkDropListDropped event once the user finishes dragging.

This was all about the new feature of DragDrop and Reordering in Angular 7, for other properties and related methods 
one can always look around the official website of Angular.

Request for Proposal

Recaptcha is required.

Sending message..