如何使用Angular7(angular material)在两个组件之间拖放 [英] How to use Angular7 (angular material) drag drop between two components
问题描述
最近 angular 引入了在 angular 材料中的拖放https://material.angular.io/cdk/drag-drop/overview.
所有示例都在单个组件中进行描述.如何在两个不同的组件中使用它,将一个组件项拖放到另一个组件中.
您可以使用属性 id 和 cdkDropListConnectedTo 来链接两个列表:
组件 1:
<div *ngFor="let item of list" cdkDrag>{{ item }}</div>
组件 2:
<div *ngFor="let item of list" cdkDrag>{{ item }}</div>
如果需要将多个列表连接到一个列表,可以使用以下语法:[cdkDropListConnectedTo]="['list-1', 'list-2', 'list-3', 'list-4']"
链接列表后,您必须根据操作正确更新一个或两个列表.您可以像这样在 drop 函数上执行此操作:
drop(event: CdkDragDrop) {if (event.container.id === event.previousContainer.id) {//在同一个列表中移动moveItemInArray(this.list, event.previousIndex, event.currentIndex);} 别的 {//在列表之间移动}}
为了在列表之间移动项目,您可能希望集中跟踪列表.您可以通过使用服务、商店或其他方法来实现.
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.
这篇关于如何使用Angular7(angular material)在两个组件之间拖放的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!