如何在组件之间使用 Angular 7 cdkDropList?

Pat*_* M. 6 drag-and-drop angular-material angular angular7

我在屏幕左侧的 mat-list 组件中有一个项目(学生)列表(常规列表)。我的屏幕右侧还有一个教室组件列表。在每个教室组件中,都有一个学生列表。

我希望能够使用角度材料的新拖放 API将学生从常规列表拖动到任何教室组件中包含的学生列表之一

伪代码如下所示:

<mat-list #studentsList="cdkDropList" cdkDropList [cdkDropListData]="students">
  <mat-list-item cdkDrag *ngFor="let student of studentes">
    {{student.name}}
  </mat-list-item>
</mat-list>

<div class="right-panel>
  <app-class-room *ngFor="let cr of classRooms" [classRoom]="cr"></app-class-room>
</div>
Run Code Online (Sandbox Code Playgroud)

显然,我无法使用[cdkDropListConnectedTo]常规列表上的输入,因为我无权访问课堂组件内的学生列表。我应该如何进行?

s-g*_*gbz 5

我想扩展之前的答案,因为我找不到适合我的场景的工作示例。请注意,我简化了这个示例以强调重要的部分(连接所需的列表)。

“实际传输逻辑”是通过 实现的(cdkDropListDropped)="onDrop($event)"。有一个非常基本的例子

1.通过cdkDropListConnectedTo连接不同组件中的特定cdkDropList

有时我们不想连接所有子组件,而只想连接某些子组件。为此,我们将使用cdkDropListConnectedTo,但我们必须为每个人提供cdkDropList一个唯一的 id。问题是它不是通常的 HTML id。

错误的方法

<component1 id="component1" cdkDropList> // <- NO!
Run Code Online (Sandbox Code Playgroud)

我们会收到这样的错误

CdkDropList could not find connected drop list with id component1
Run Code Online (Sandbox Code Playgroud)

正确的方法

文档指出有一个专用属性。因此连接列表的正确方法是:cdkDropList@Input()id

CdkDropList could not find connected drop list with id component1
Run Code Online (Sandbox Code Playgroud)

您现在只能从组件 1 拖动到组件 2。

请注意,id本例中的 是一个字符串。我们必须将字符串包装起来' '才能将它们传递给@Input()(如果您不熟悉的话,这里有一个小指南)。

2. 使用 cdkDropListGroup 指令连接所有 cdkDropList

添加cdkDropListGroup到父元素会连接所有子元素并允许在它们之间拖动。cdkDropListGroup 文档

<component1 [id]="'component1'" [cdkDropListConnectedTo]="'component2'" cdkDropList></...>
<component2 [id]="'component2'" cdkDropList></...>
<component3 [id]="'component3'" cdkDropList></...>
Run Code Online (Sandbox Code Playgroud)

每个项目都可以在组件 1、2 和 3 之间传输。cdkDropListGroup 指令的工作示例


编辑:这是一个包含两个组件的工作示例


ibe*_*oun 3

You can use string instead of reference as mentionned in the API documentation :

@Input('cdkDropListConnectedTo') connectedTo: (CdkDropList | string)[] | CdkDropList | string

Other draggable containers that this container is connected to and into which the container's items can be transferred. Can either be references to other drop containers, or their unique IDs.

I made an example using a list of all dropable elements ids.

allDropLists = [ 'studentsList', ...this.classRooms
 .map(_ => _.name)];
Run Code Online (Sandbox Code Playgroud)

Which I pass to the ClassRoomComponent as an input :

<app-class-room
    *ngFor="let classRoom of classRooms" 
    [classRoom]="classRoom" [allDropLists]="allDropLists">
Run Code Online (Sandbox Code Playgroud)

The complete running example is here.