您需要将“字符串”数组转换为“对象”数组
想象一下,您有一系列项目,例如
[{task:"eat breakfast",order:0},
{task:"eat lunch",order:1},
{task:"eat dinner",order:2}
]
在您的放置功能中,您需要重新计算属性顺序。使用典型的 drop 函数
drop(event: CdkDragDrop<any[]>) {
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
transferArrayItem(event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex);
//if transfer, recalculate the order of previous (the list from drag)
event.previousContainer.data.forEach((x,index)=>{
x.order=index
})
}
//always, recalculate the order of the container (the list to drag)
event.container.data.forEach((x,index)=>{
x.order=index
})
}
然后你无论如何都需要保存数据(我认为你可以使用ngOnDestroy),当你收到数据时不要忘记按顺序排序
注意:在这个 SO中有一个使用 formArray 的 cdkDragList (仅用于排序)如果你想使用 FormArray 但它不是必需的,只有两个数组必须足够