拖拽功能在Angular官方组件库material中有,即为DragDropModule。
一般功能在文档中都有提及,也比较好理解,不赘述。但在多行多列布局中的拖拽排序,用普通的排序会有问题(预览位置错乱,无法落位正确),官方没有给出明确的方案。
解决方法
将list-item的结构整体提升,采用group-list-item结构。
整个功能布局视为group,一个拖动项为单list-单item,这样拖动排序时,会视作item拖到另一个拖动项的list中,完成后会进行排序。
拖拽预览时,会出现一个list中有两个item的情况,需要写点样式代码隐藏一个item。
代码
以这部分代码作为基础模板
修改代码如下
html
<div cdkDropListGroup class="example-list">
<div
class="example-box"
*ngFor="let movie of movies; let i = index"
cdkDropList
(mousedown)="getIndex(i)"
[cdkDropListData]="movies"
(cdkDropListDropped)="drop($event, i)"
>
<div cdkDrag>
{{ movie }}
</div>
</div>
</div>
ts
getIndex(index: number) {
this.curIndex = index;
}
drop(event: CdkDragDrop<string[]>, i: number) {
if (event.previousContainer !== event.container) {
transferArrayItem(
event.previousContainer.data,
event.container.data,
this.curIndex,
i
);
}
}
less
&.cdk-drop-list-dragging {
.cdk-drag:not(.cdk-drag-placeholder) {
display: none !important;
}
}