How to create drag and drop accordion list in Angular

In this article, I’d like to share with you how to create a list of accordion items, which also supports the drag and drop functionality.

We will build two lists, the first is the list of unassigned tasks, and the second is the list of assigned tasks. Users can drag each task and reorder it within the list, or move it from one list to another list.

The end result of this tutorial is as follows.

How to create drag and drop accordion list in Angular

So let’s get started…

First we need to import two modules DragDropModule and MatExpansionModule from Angular material.

import { DragDropModule } from '@angular/cdk/drag-drop';

import { MatExpansionModule } from '@angular/material';

To build the accordion list, we need some mock data to display. In the component class, we declare two lists of data, the first is unassignedTasks and the second is assignedTasks.

How to create drag and drop accordion in Angular — variable declaration
Declare mock data for drag and drop accordion list

In order to make the list item data type-safe, we define an interface for it, for the sake of simplicity, it will contain only the ID, title, and description.

How to create drag and drop accordion in Angular — interface declaration
Declare interface for each list item

Next, we will use the mat-accordion and mat-expansion-panel of Angular material to create a list of accordion panels for unassigned tasks. We also do the same for assigned tasks list.

So now we have two lists of accordion items.

Next, we will add the drag and drop functionality for every list by adding the cdkDropList directive to mat-accordion component, and cdkDrag to mat-expansion-panel component.

How to create drag and drop accordion in Angular — add drag and drop functionality
Add drag and drop functionality to accordion panel list

Here, we add the line [cdkDropListConnectTo]="[assignedList]" to allow the user to drag an item from this list and drop it to the assigned task list.

The drop method will look like this.

How to create drag and drop accordion in Angular — define drop method
Drop method

If the drop is in another container, then we need to move it to that container. Once it is correctly located we can move the item around.

Dont’ forget to import the methods to make it work!

And that’s it.

We have built two lists of accordion panel, which also have the drag and drop functionality supported.

You can find the full example code at the link here https://stackblitz.com/edit/angular-accordion-drag-and-drop

Thanks for reading and have a great day!

Angular Enthusiast