As recently angular introduced drag and drop in angular material https://material.angular.io/cdk/drag-drop/overview .
All examples describes with in a single component. How to use this in two different components, Drag one component item and drop into another component.
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, sorting within a list, transferring items between lists, animations, touch devices, custom drag handles, previews, and placeholders, in addition to horizontal lists and ...
To implement drag and drop list you have to include your ngFor repeated section inside a parent div to make that section draggable. This is just a basic structure of how the draggable section should look. Now we have to provide DndList directives to this structure. Basic functioning HTML for drag and drop list.
You may use properties id and cdkDropListConnectedTo to link both lists:
Component 1:
<div cdkDropList id="list-1" cdkDropListConnectedTo="list-2" (cdkDropListDropped)="drop($event)"> <div *ngFor="let item of list" cdkDrag>{{ item }}</div> </div>
Component 2:
<div cdkDropList id="list-2" cdkDropListConnectedTo="list-1" (cdkDropListDropped)="drop($event)"> <div *ngFor="let item of list" cdkDrag>{{ item }}</div> </div>
If you need to connect several lists to one list, you may use the following syntax: [cdkDropListConnectedTo]="['list-1', 'list-2', 'list-3', 'list-4']"
After linking the lists, you must correctly update one or both lists depending on the actions. You may do it on the drop function like this:
drop(event: CdkDragDrop<string[]>) { if (event.container.id === event.previousContainer.id) { // move inside same list moveItemInArray(this.list, event.previousIndex, event.currentIndex); } else { // move between lists } }
For moving items between lists, you will possibly want to keep track of the lists centrally. You may do so by using a Service, a Store or other methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With