Angular v14 - CurrentIndex/PreviousIndex always 0 when dropping items using Angular Material CDK Drag and Drop

207 views Asked by At

We are using Angular v14 with Angular Material. We are currently using the CDK drag&drop to drag and drop (sub-)items in a nested structure. When we drop an (sub-)item, the previousIndex and currentIndex are always 0, which means I cannot drop an item to a specific location.

I expect to drop an item on the location I requested. Does anybody has an idea how to solve this? https://stackblitz.com/edit/angular-cdk-nested-drag-drop-demo-4m1wqg

Detailed explaining: The page consist of multiple phases. Each phase is represented as a column. Each phase contains one or more items. Each item contains one or more subitems. All concepts are represented as an Item

We need to drag and drop items and subitems within the same phase, but also to another phase. Items and subitems are interchangeable, meaning: if you drop a subitem on the level of an item, the subitem will become an item. Also the way around, when you drop an item to the level of a subitem, the item becomes a subitem.

Because the previousIndex and the currentIndex are always 0, we cannot determine the location where we want to drop an item/subitem. The item is always added to the end of that list.

Example The examples I found on the web are providing only pieces of my drag and drop solution. I created a stackblitz sample based on another sample on the internet containing my problem: previousIndex and the currentIndex are 0 when you drop an item or subitem.

I expect to drop an item on the location I requested.

https://stackblitz.com/edit/angular-cdk-nested-drag-drop-demo-4m1wqg (the sample was based on angular v8, but upgrading the package.json to v14 did not solved the issue)

1

There are 1 answers

0
highlander-dev On

Ah, the joys of Angular CDK drag-and-drop with nested lists, right? Seeing 'previousIndex' and 'currentIndex' stuck at 0 is a classic issue. It's mostly about Angular needing some help to keep track of everything.

Quick tips:

  • Double-check your data bindings. Angular loves unique identifiers for each item. If they're missing or if you're not using 'trackBy', that could be the culprit.
  • Custom logic might be your friend here. Calculating drop positions based on the drag event's position can help, especially with the nested structure.
  • Make sure your lists are chatting nicely with each other. Proper setup for interconnected lists is crucial.
  • Dive into the drop event details. There's usually more info there that can guide you.
  • Keep everything up-to-date. Sometimes, just updating Angular and CDK can solve these quirky issues.
  • And, of course, the Angular community is a goldmine. Someone might have faced and solved this exact problem. In fact, I recently just found out that HeroDevs is actually supporting ng v6-15 now post-EOL.

A bit of detective work and some tweaking should get you past this hurdle. Good luck!