[Fixed] Angular material drag drop cdk: Combining items into one and swapping the elements


With reference to Angular CDK Drag & Drop, I’m trying to build something shown in the video below:


I want to achieve two features together: Merging cards and swapping the positions of items. I don’t find this feature available in Angular material.

So I tried a hack:

enter image description here

In this above image assume 1,2,3,4,5,6 are my array values and 0,1,2,3,4,5 are my array indexes.

I tried a logic to identify merge and swap case:
enter image description here

Note: Added -1 id record before and after the real element.

Merge case is:
from a previousIndexValue > -1 && currentIndexValue > -1 (except before/after of current
Swap case

The code is:

const previousIndex = event.previousIndex;
    const currentIndex = event.currentIndex;
    const prevSiblingIndex = previousIndex - 1;
    const nextSiblingIndex = previousIndex + 1

    if (currentIndex === prevSiblingIndex || currentIndex === nextSiblingIndex) {
      return true;
    const previousCard = cards[previousIndex].id;
    const currentCard = cards[currentIndex].id;

    if (previousCard === currentCard) {
      return true;

    if (previousCard > -1 && currentCard > -1) { console.log("Merge") }
    else { console.log("Swap"); }

The above logic works fine for me if the -1(fake element) has the same height and visible in the container as shown in the video below:


But if I hide/opacity = 0/set visibility hidden the logic starts identifying swap as merge.

The above logic doesn’t seem to be working for me, whenever I drop the card for swap the above logic gives "Merge".

Here is the demo link: Stackblitz demo


I wrote a custom solution since it is not available anywhere


Leave a Reply

(*) Required, Your email will not be published