angular/cdk 简单拖动不适用于带有 ngFor 的 div

Nee*_*enu 2 drag-and-drop drag ngfor angular angular-cdk

我需要使用 angular-cdk 制作可拖动的项目。我已经在 app 模块中导入了 DragDropModule。我正在 ngFor 中应用 cdkDrag。

<div *ngIf="messages.length" >
    <div
      *ngFor="let message of messages" cdkDrag>
      <strong>{{ message }}</strong>
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

拖动没有按预期工作,控制台中也没有出现错误。拖动功能适用于普通 div 元素。

Joh*_*ord 14

除了M. Doe的回答之外,我还必须执行以下操作:

将以下内容添加到我的 app.module.ts 文件中:

import { DragDropModule } from '@angular/cdk/drag-drop';
...
imports:
[
    DragDropModule
]
Run Code Online (Sandbox Code Playgroud)

将 cdkDropListData 参数添加到包含要排序的项目列表的父元素中:

<div cdkDropList [cdkDropListData]="messages" (cdkDropListDropped)="drop($event) *ngIf="messages.length" >
    <div
      *ngFor="let message of messages" cdkDrag>
      <strong>{{ message }}</strong>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)


M. *_*Doe 8

您应该添加cdkDropList到外部 div 以及放置事件。

拖放 CDK

组件.html

<div cdkDropList (cdkDropListDropped)="drop($event)" *ngIf="messages.length" >
    <div
      *ngFor="let message of messages" cdkDrag>
      <strong>{{ message }}</strong>
    </div>
  </div>
Run Code Online (Sandbox Code Playgroud)

组件.ts

drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.messages, event.previousIndex, event.currentIndex);
  }
Run Code Online (Sandbox Code Playgroud)