angular/cdk simple drag not working for div with ngFor
Asked Answered
D

4

10

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.

Dingo answered 3/6, 2019 at 12:29 Comment(0)
C
29

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>
Crossness answered 24/10, 2019 at 18:26 Comment(1)
This was my issue as well. However, shouldn't there be an error thrown if the module isn't properly imported?Dissert
B
12

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);
  }
Bharat answered 3/6, 2019 at 12:36 Comment(3)
what is moveItemInArray()Dingo
I got it. thank you ; import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';Dingo
stackblitz.com/angular/… Remove the strong tag so the div is the looped child. Then add the font-weight: 700 to the div class to replicate a strong classBharat
M
2
  1. You should add DragDropModule into module where the component is declared
  2. The *ngFor directive works with cdkDrag directive without cdkDropList
Moan answered 25/7, 2021 at 9:3 Comment(0)
I
1

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

Iatrochemistry answered 24/10, 2020 at 20:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.