To-Do list using Drag and Drop in Angular 7

Image courtesy: Demos with Angular

The new version of Angular came out with many new features and one of them is Drag and Drop Module. In this article we would be exploring the new Drag and Drop feature that is included in Angular Material by creating a To-Do list.

Getting Started

To begin, add or update the @angular/cdk dependency in package file of your project or run one of the following commands:

npm install @angular/cdk@7.0.0-beta.0
OR
yarn add @angular/cdk@7.0.0-beta.0

Now, include package in your app.module.ts

import { DragDropModule } from '@angular/cdk/drag-drop';
@NgModule({
imports: [BrowserModule, FormsModule, DragDropModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }

Now, to make an element drag-able, all you have to do is to add the cdkDrag directive on the element. And there you go! So simple, isn’t it ?

Sort-able List

One common use-case of Drag & Drop is sorting or reordering lists which is useful to create a to-do list. Just apply cdkDrag directive to the list items and enclose the list within the cdk-drop element and you’re good to go!

You can create cdk-drop elements that will tell the CDK that the draggable item is only allowed to drop inside this drop-zone. Also, the best part is you can customize drag and drop animation as you want.

After dropping the item, the list remains unchanged. This is because Angular CDK just drops the item and the list remains unchanged until you handle the drop event and use Angular CDK’s moveItemInArray method which on drop rearrange the items array according to the indexes.

If the user is dragging an element within the same container, we perform a sortable action; otherwise, we transform the value from one collection to the other using the built-in transferArrayItem() method.

The cdk-drop component supports transferring dragged items between connected drop zones. You can connect one or more cdk-drop instances by setting the connectedTo property.

CdkDragPreview

When a cdkDrag element is picked up, it will create a preview element visible while dragging. By default, this will be a clone of the original element positioned next to the user's cursor. This preview can be customized, though, by providing a custom template via *cdkDragPreview.

And that’s it, finally your To-Do list looks like this.

The complete code for this sample can be found here:

Web Developer, loves to write about UI technologies

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store