angular/cdk simple drag not working for div with ngFor
11,445
Solution 1
You should add cdkDropList
to your outer div, aswell as a drop event.
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);
}
Solution 2
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>
Solution 3
- You should add DragDropModule into module where the component is declared
- The *ngFor directive works with cdkDrag directive without cdkDropList
Author by
Neenu Chandran
Updated on June 13, 2022Comments
-
Neenu Chandran almost 2 years
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.