components icon indicating copy to clipboard operation
components copied to clipboard

[cdkDragDrop] CopyArrayItem: items somehow connected

Open justAnormalUser00 opened this issue 7 years ago • 5 comments

I dont now if i am stupid or this is a bug... i asked several people and no one seems to know the answer.

What are the steps to reproduce?

https://stackblitz.com/edit/angular-yr8ej6

1.) drag one item to the right container 2.) click on test button

What is the expected behavior?

click on test button should only change the value of the item in the right container on position 0 of the array

What is the current behavior?

click on test button changes both values

Which versions of Angular, Material, OS, TypeScript, browsers are affected?

Angular: 7.2.8 @angular/cdk 7.3.7

justAnormalUser00 avatar May 14 '19 15:05 justAnormalUser00

It's because copyArrayItem only adds a reference to the new array, it doesn't actually do a deep copy of the object.

crisbeto avatar May 15 '19 19:05 crisbeto

thanks for the answer, is there a simple way to make a real copy?

justAnormalUser00 avatar May 15 '19 21:05 justAnormalUser00

The CDK doesn't provide a deep copy function out-of-the-box, but there are lots of solutions out there. E.g. something like this should do the trick in lodash:

import {cloneDeep} from 'lodash';

onTalkDrop(event: CdkDragDrop<Element[]>) {
  if (event.previousContainer !== event.container){
    // Clone the item that was dropped.
    const clone = cloneDeep(event.previousContainer.data[event.previousIndex]);

    // Add the clone to the new array.
    event.container.data.splice(event.currentIndex, 0, clone);
  }
  else{
    moveItemInArray(
      event.container.data,
      event.previousIndex,
      event.currentIndex
    );
  }
}

crisbeto avatar May 16 '19 04:05 crisbeto

THANKS a lot :D works like a charm.

justAnormalUser00 avatar May 16 '19 08:05 justAnormalUser00

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.