After looking for a long time I was not able to find a complete solution at a single place and had to take references from various sources as there was no solution particularly for Angular 6. Angular material provides an in-built drag and drop solution, but only from angular 9.
I found an npm package “ngx-drag-and-drop-lists” but it didn’t have any implementation examples that made the implementation easier. So I decided to write a full-fledge solution to the problem.
First of all, install the npm package using the command
npm i ngx-drag-and-drop-lists@1.2.5
Note- version 1.2.5 and below are stable for angular 6, greater versions might not be supported by Angular 6.
There might be some error while installing the package, looking like this.
This error occurs when an npm package has a post-install script and it fails to execute or complete.
To overcome this issue you have to install the package by ignoring the post-install script.
npm install ngx-drag-and-drop-lists@1.2.5 — ignore-script
Now after your npm package is installed you are good to use it in your application.
Import the “DndListModule” inside your required module
import { DndListModule } from ‘ngx-drag-and-drop-lists’;
and add “DndListModule” in the imports array.
Drag and drop list work on the array data type. So let’s assume you have an array which is ngFor repeated and you want to implement drag and drop list to adjust the indexes of the elements present in that array.
To implement drag and drop list you have to include your ngFor repeated section inside a parent div to make that section draggable.
Now we have to provide DndList directives to this structure.
[dndList] is used to make the particular div a draggable area where all the drag and drop operation will be supported.
[dndModel] is used to specify on which array variable drag and drop and index manipulation will be done.
[dndPlaceholder] is used to specify an id of an element that will act as a place holder when dragging is being done.
Notice that I have added an extra div just before the ng-repeated list and given it id “placeholder”. This div acts as a placeholder when dragging is being done. CSS for the div is given below.
[dndDraggable] is used to define which element will be draggable.
[dndObject] is used to define when an item is being dropped or dragged, what value will it store.
(dndMoved) is the output event that will be triggered when an element is dropped. We have to provide our array manipulation logic in that function.
This will rearrange the array and place the item at the index at which the item was dropped.
This is a basic example of how drag and drop lists can be implemented in an Angular 6 application. There can be various modifications that can be done both on the logical side and the UI side. Set your imagination horses free and enjoy this wonderful feature as we did in Fibotalk.