2
votes

I need to make an item draggable with angular-cdk. I have imported the DragDropModule in the app module. I am applying the cdkDrag inside an ngFor.

<div *ngIf="messages.length" >
    <div
      *ngFor="let message of messages" cdkDrag>
      <strong>{{ message }}</strong>
    </div>
  </div>

The drag is not working as expected, also no errors are appearing in the console. The drag feature works for normal div elements.

4

4 Answers

8
votes

You should add cdkDropList to your outer div, aswell as a drop event.

Drag and drop CDK.

component.html

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

component.ts

drop(event: CdkDragDrop<string[]>) {
    moveItemInArray(this.messages, event.previousIndex, event.currentIndex);
  }
14
votes

In addition to M. Doe's answer, I had to do the following:

Add the following to my app.module.ts file:

import { DragDropModule } from '@angular/cdk/drag-drop';
...
imports:
[
    DragDropModule
]

Add the cdkDropListData parameter to my parent element that contains the list of items to sort:

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

Removing class attribute from cdkDrag element fixed drag drop in my case.

0
votes
  1. You should add DragDropModule into module where the component is declared
  2. The *ngFor directive works with cdkDrag directive without cdkDropList