要防止元素在没有放入容器时返回,可以使用Angular Material的cdkDropList指令的cdkDropListEnterPredicate属性。
首先,确保你已经正确导入了DragDropModule和CdkDragDrop相关的模块和指令。然后,可以按照以下步骤进行操作:
isDropped: boolean = false;
cdkDropList指令,并绑定cdkDropListEnterPredicate属性到一个方法上:
canEnterDropZone方法,用于控制元素是否可以进入容器:canEnterDropZone(event: CdkDragEnter): boolean {
// 检查元素是否已经放入容器
if (this.isDropped) {
return true; // 允许元素进入容器
} else {
return false; // 不允许元素进入容器
}
}
isDropped变量设置为true:onDrop(event: CdkDragDrop) {
// 验证元素是否已经放入容器
if (!this.isDropped) {
// 设置元素为已放入容器
this.isDropped = true;
// 处理元素放入容器的逻辑
// ...
}
}
这样,当元素没有放入容器时,将不会返回到原始位置。
请注意,如果你使用了cdkDropListGroup指令来管理多个cdkDropList容器,你需要适当地设置cdkDropListEnterPredicate属性以适应你的需求。