angularangular-cdk-drag-drop

only apply cdkDragHandle to the header in child component


I want the drag component present as a popup floating on the screen, and user only can move the popup by dragging the header. However, the cdkDrag is applied on the parent component. So it can still moved by dragging outside the header.

app.component.ts

<app-popup
    cdkDrag
    cdkDragBoundary=".body-container"
    [cdkDragFreeDragPosition]="{ x: -10, y: 0 }"
    [style.width]="'150px'"
    [style.height]="'150px'"
  >
  </app-popup>

app.component.css

app-popup {
  position: absolute;
  right: 20px;
  top: 0;
  z-index: 9999;
}

popup.component.ts

<app-item></app-item>

item.component.ts

<div class="item">
  <div class="item-header">Drag Here !</div>
  <div class="item-content">Please no drag by here.</div>
</div>

item.component.css

.item-header {
  cursor: move;
  background-color: red;
  height: 30px;
  text-align: center;
}

Please tell me how to only apply the cdkDragHandle to the header. Thank you.

StackBlitz - cdkDrag


Solution

  • cdkDragHandle is the directive designed for these kind of situations https://material.angular.io/cdk/drag-drop/api#CdkDragHandle

    The slight problem here is that is needs to be applied to a direct descendant of the draggable element that has cdkDrag. To achieve this the dragged header could be pass through as the content of popover down to the parent.

    Updated stack blitz

    The above fix does not have the styles applied, but this could be resolved by having a separate component for the header.