Angular CDK拖拽:如何阻止拖拽项临时显示在目标按钮容器中?
Angular CDK拖拽:阻止拖拽项临时进入按钮容器显示
问题说明
已实现组件1到组件2的基础CDK拖拽功能,拖拽与事件触发均正常。但拖拽组件1的项到组件2的按钮容器时,拖拽项会作为按钮的子元素临时显示,需在保持其他功能正常的前提下阻止该现象。
尝试过以下方法但未解决:
- 使用
OnDropListEnterPredicate返回false:导致落放功能失效 - 通过
cdkDropListEntered事件移除拖拽项:未解决问题
解决方案
方法1:将拖拽预览挂载到body
给组件1的拖拽项添加cdkDragRootElement="body",让拖拽时的预览元素附加到body下,而非进入按钮容器内部,从根源避免临时显示问题。
修正后的组件1代码:
<div cdkDropList [cdkDropListConnectedTo]="['tool-table-drag1']" id="draggable-list"> <div class="container" *ngFor="let item of items" cdkDrag cdkDragRootElement="body"> <div class="item-container">{{ item.name }}, - {{item.toolTypeName}}</div> </div> </div>
注意:移除了原代码中重复的
cdkDrag指令(原item-container元素上的cdkDrag),一个拖拽项只需在最外层容器添加一次cdkDrag。
方法2:自定义拖拽预览模板
通过*cdkDragPreview定义拖拽时显示的独立预览内容,替代默认的拖拽行为,原元素不会被临时插入目标容器。
修正后的组件1代码:
<div cdkDropList [cdkDropListConnectedTo]="['tool-table-drag1']" id="draggable-list"> <div class="container" *ngFor="let item of items" cdkDrag> <div class="item-container">{{ item.name }}, - {{item.toolTypeName}}</div> <!-- 自定义拖拽预览 --> <ng-template *cdkDragPreview> <div class="item-container">{{ item.name }}, - {{item.toolTypeName}}</div> </ng-template> </div> </div>
组件2代码无需修改
原组件2的drop方法逻辑保持不变,event.isPointerOverContainer仍能正常判断拖拽是否落在按钮容器内,不影响落放事件触发。
内容的提问来源于stack exchange,提问作者xLipeq
相关产品推荐
相关产品推荐

