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/
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
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
</div>
With Drag and Drop we also have Reordering lists feature:
Code Example:
HTML:
<div cdkDropList class="example-list" (cdkDropListDropped)="drop($event)">
<div class="example-box" *ngFor="let list of cars" cdkDrag>{{cars}}</div>
</div>
TS Code:
import {Component} from '@angular/core';
import {CdkDragDrop, moveItemInArray} from '@angular/cdk/drag-drop';
/**
* @title Drag&Drop sorting
*/
@Component({
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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Himanshu Agarwal
He works on Frontend Technologies like Javascript, Angular, HTML, CSS, jQuery.