Search code examples
angulardrag-and-dropangular-cdk

cdkDragHandle doesn't work inside child component


Using @angular/cdk 7.2.1: If defining a parent component holding a cdkDropList and a nested list of cdkDrag components, defining a cdkDragHandle inside the nested child component doesn't work. If the same structure is all in the same component, cdkDragHandle works perfectly.

https://stackblitz.com/edit/angular-wfvmuj?embed=1&file=src/app/hello.component.html

Has anyone found a fix to get cdkDragHandle to work even when not defined in the same component as cdkDrag?


Solution

  • This solution worked for me:

    Parent Component:

    <div cdkDropList #list="cdkDropList"
      [cdkDropListData]="myArray"
      (cdkDropListDropped)="drop($event)">
    
      <app-item
        *ngFor="let item of myArray"
        cdkDrag>
        <div cdkDragHandle></div>
      </app-item>
    
    </div>
    

    Child Component (app-item):

    <div class="drag-container">
      <ng-content></ng-content>
      <div class="drag-handle">drag here</div>
    </div>
    

    Then style the cdk-drag-handle class in the parent component. cdk-drag-handle comes with material, so we do not need to apply it manually:

    .cdk-drag-handle {
       width: 100%;
       height: 100%;
       position: absolute;
       z-index: 100;
       background-color: transparent;
       cursor: move;
     }
    

    Then style the drag-container with position: relative and whatever you want. I have an item inside it (drag-handle) which also takes the full width and height of the container, that contains an image (just as a sidenote).