1

I'm using a drag and drop list for a user to arrange items in the proper order. The issue I'm having is that there currently is a setTimeout in my code because the method to retrieve the order of the list is not instantly updated on drop. I suspect it updates after the animation or something.

HTML

<div class="sort-order" cdkDropList *ngIf="parsedInteraction?.optionsSortOrder"
    [cdkDropListData]="parsedInteraction?.optionsSortOrder" (cdkDropListDropped)="sortOrderDrop($event)">
    <div class="sort-order-draggable" *ngFor="let item of parsedInteraction?.optionsSortOrder" cdkDrag
        [cdkDragData]="item">
        <div *ngIf="item?.picture" [innerHTML]="item.picture | safeHtml"></div>
        <div *ngIf="item?.option" [innerHTML]="item.option | safeHtml"></div>
    </div>
</div>

TS

sortOrderDrop(event: CdkDragDrop<InteractionOptionSortOrder[]>) {
  moveItemInArray(
    event.container.data,
    event.previousIndex,
    event.currentIndex
  );

  // How to remove this ugly thing?
  window.setTimeout(() => {
    this.currentSortOrder = (
      event.container.getSortedItems() as CdkDrag<InteractionOptionSortOrder>[]
    )
      .map((draggable) => draggable.data.position)
      .join(',');
  }, 100);

  this.hasDragged = true;
}

How do I get rid of the timeout if I want to know the current sort order?

Jonathan
  • 8,771
  • 4
  • 41
  • 78

2 Answers2

1

It turns out event.container.data holds the correct order after the moveItemInArray method. Still wondering why getSortedItems is delayed and how this is supposed to work.

moveItemInArray(
  event.container.data,
  event.previousIndex,
  event.currentIndex
);

this.currentSortOrder = event.container.data
  .map((draggable) => draggable.position)
  .join(',');
Jonathan
  • 8,771
  • 4
  • 41
  • 78
0

you have event.previousIndex, event.currentIndex then just store that order in some variable before moveItemArray()

Ravi Gajera
  • 169
  • 6