You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中DragDropModule在template模板内无法正常生效问题

解决方案

核心原理是绕过CDK自动查找父级cdkDropList的逻辑,手动给模板内的cdkDrag绑定投放容器引用,完全适配递归渲染场景。

具体修改步骤

  1. 给外层的cdkDropList添加模板引用变量,指定导出为cdkDropList
  2. 使用ngTemplateOutlet渲染模板时,将dropList引用通过上下文参数传入模板
  3. 模板内部接收传入的引用,绑定到cdkDrag的cdkDropList输入属性上

修改后代码示例

<!-- 外层投放容器,增加模板引用 -->
<div
  cdkDropList
  #activityDropList="cdkDropList"
  [cdkDropListData]="expanded.activities"
  (cdkDropListDropped)="dropActivity($event)"
>
  <div *ngFor="let activity of expanded.activities">
    <!-- 传入dropList引用到模板上下文 -->
    <ng-container 
      [ngTemplateOutlet]="orangeProgramActivity" 
      [ngTemplateOutletContext]="{ targetDropList: activityDropList }"
    ></ng-container>
  </div>
</div>

<!-- 模板接收上下文参数,绑定cdkDropList -->
<ng-template #orangeProgramActivity let-targetDropList="targetDropList">
  <div cdkDrag [cdkDropList]="targetDropList">This is just a test</div>
</ng-template>

递归场景适配

如果是多层递归渲染,只需要在每一层的投放容器处把当前层的dropList引用作为上下文参数传递给下一层递归模板即可,逻辑完全复用。


内容的提问来源于stack exchange,提问作者vollukas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 05:12:00