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.


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.


Not sure if the above solution still works with angular 7.2.9 and angular material/cdk 7.3.5

It did not work for me and thus after some hard time - I managed to make it work using cdkDropListGroup directive. All cdkDropList within cdkDropListGroup will be available to drop items. You no longer need to connect Drop Lists with cdkDropListConnectedTo property

<div cdkDropListGroup>
<component1></component1>
<component2></component2>
</div>