Search code examples
angulardrag-and-dropdragngforangular-cdk

angular/cdk simple drag not working for div with ngFor


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.


Solution

  • 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>