Angular material cdk drag and drop, how to get target(mouse target) element?

2.1k Views Asked by At

I couldn't find any documentation on how to get the target of dropped element using cdk drag drop. below is the sample code dragging item from box1 div to Shoppingbasket div. here im expecting target should be box2 div. but I'm receiving Shoppingbasket div.here is the stackblitz example

HTML

<div cdkDropListGroup>
  <div class="example-container">
    <h2>Available items</h2>
    <div cdkDropList [cdkDropListData]="items" class="example-list" cdkDropListSortingDisabled
        (cdkDropListDropped)="drop($event)">
        <div id="box1" class="example-box" *ngFor="let item of items" cdkDrag>{{item}}</div>
    </div>
  </div>
  <div class="example-container2">
    <h2>Shopping basket</h2>
    <div id="Shoppingbasket" cdkDropList [cdkDropListData]="basket" class="example-list"
        (cdkDropListDropped)="drop($event)">
        <div id="box2" class="example-box1" cdkDragHandle></div>
    </div>
  </div>
</div>          

TS

   drop($event){
      if (event.previousContainer === event.container) {
          moveItemInArray(event.container.data, event.previousIndex,event.currentIndex);
      } else {
         transferArrayItem(event.previousContainer.data,event.container.data,event.previousIndex);
      }
   }
1

There are 1 best solutions below

0
On

There's no event.target in the cdk drag and drop events but you can manually add the attribute to the event object when needed like this :

event.target = event.container.element.nativeElement;