mark
mark

Reputation: 105

Obtains the name and ID of the dropped element

I am using the cdk drag and drop library to drag and drop objects.

My problem is that I am not able to obtain the data (object information: name and ID) of the dropped object.

I've tried using console.log (event.item.data) but it gives undefined.

Does anyone know how I can get the information about the dropped element?

Thanks

Stackblitz - Demo

.ts

 drop(event: CdkDragDrop<string[]>) {
    console.log(event.item.data)
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    }
  }

html

<div class="six" style=" height: 75%;">
  <div class="card-deck cardsZone">
    <div class="card myCards">
      <div class="card-body" style="overflow-y: auto;"  #activeList="cdkDropList"
      class="box-list" style="height:100%"
      cdkDropList
      cdkDropListOrientation="vertical"
      [cdkDropListData]="A"
      [cdkDropListConnectedTo]="[inactiveList]"
      (cdkDropListDropped)="drop($event)">
        <div *ngFor="let nw of A" cdkDrag>
        <div class="card mysmallCcards">             
          <div class="card-body">
                   <span>{{nw.name}}</span>         
          </div>
        </div>
        </div>
      </div>
    </div>
    <div class="card myCards">
      <div class="card-body" style="overflow-y: auto;" #inactiveList="cdkDropList"
      class="box-list" style="height:100%"
      cdkDropList
      cdkDropListOrientation="vertical"
      [cdkDropListData]="B"
      [cdkDropListConnectedTo]="[activeList]"
      (cdkDropListDropped)="drop($event)">
        <div *ngFor="let pr of B" cdkDrag>
        <div class="card mysmallCcards">
          <div class="card-body">
           <span>{{pr.name}}</span>
          </div>
        </div>
        </div>
      </div>
    </div>
  </div>
</div>

Upvotes: 5

Views: 8818

Answers (3)

Dragging within or across the container use event.previousContainer.data[event.currentIndex]

To get the item ID use event.container.data[event.currentIndex]['id']

Upvotes: 0

Frederick
Frederick

Reputation: 872

The data of the item is just an input. The documentation for it is:

@Input('cdkDragData') data: T

Arbitrary data to attach to this drag instance.

So, to add the data to the event, you have to set it for each draggable element. Like this:

<div *ngFor="let nw of A" cdkDrag [cdkDragData]="nw">

Upvotes: 5

Leandro Matilla
Leandro Matilla

Reputation: 1011

Try with this:

event.previousContainer.data[event.previousIndex]

If you want the id of the item:

event.previousContainer.data[event.previousIndex]['id]

Upvotes: 9

Related Questions