Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Angular7 (angular material) drag drop between two components

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.

like image 979
Jomy Joseph Avatar asked Nov 21 '18 13:11

Jomy Joseph


People also ask

Does angular support drag and drop?

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 ...

How do you drag and drop in angular 6?

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.


1 Answers

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.

like image 87
GCSDC Avatar answered Sep 17 '22 04:09

GCSDC