首页 > 解决方案 > 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.

标签: angulardrag-and-dropangular-materialangular7angular-cdk

解决方案


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.


推荐阅读