Am Struggling lot to complete my task as newly started into Angular CDK DragnDrop. When trying to drag the image item and drop into location, I got Cannot read properties of undefined (reading 'length') .
Not sure this is because of different Interface against Angular DragnDrop CDK
drop(event: CdkDragDrop<any>) {
if (event.previousContainer === event.container) {
moveItemInArray(
event.container.data,
event.previousIndex,
event.currentIndex
);
} else {
transferArrayItem(
event.previousContainer.data,
event.container.data, // getting undefined here
event.previousIndex,
event.currentIndex
);
console.log(
'transferArrayItem',
event.container.data.colorways
);
const formArry = this.myDivName;
formArry.insert(0, this.fb.control(event.container.data));
}
}
does event.container.data, pointing to drop location or source location?
CodePudding user response:
Here you go
/* Add initial empty data */
imgSource: Pokedex = {
colorways: [],
count: 0,
};
drop(event: CdkDragDrop<any>) {
...
else {
transferArrayItem(
event.previousContainer.data,
event.container.data, //remove colorways, event.container.data?.colorways,
event.previousIndex,
event.currentIndex
);
}
<!-- Left container -->
[cdkDropListData]="colorways" <!-- Wrong -->
[cdkDropListData]="colorways.colorways" <!-- Right -->
<!-- Right Container -->
[cdkDropListData]="imgSource" <!-- Wrong -->
[cdkDropListData]="imgSource?.colorways" <!-- Right -->
CodePudding user response:
The best way to understand the cdkDropList is forget the cdkDropList. We need think simply in two arrays of object
The cdkDropList is only an interface to change the position of the elements of the arrays or to move one element of the array to the another one. We can imagine two simple inputs and three buttons, the first buttons interchange the position of one element in one array and in the another one and the last button interchange the elements of the two arrays
The functions moveItemInArray and transferArrayItem are only javascript function. We can see the definition this and we can use or not (*)
The $event that emit an event (cdkDropListDropped) is type of CdkDragDrop, so we have
- container, the cdkDropList where is dropped -so we have in the event.container.data the array we indicate in [data] or the cdkDropList
- previousContainer, idem about the ckdDropList from we start drag
- currentIndex, the index (position) of the element in array event.container.data where is dropped
- previousIndex, the index (position) of the element in array of event.previousContainer.data
So, the data of your cdkDropList should be colorways.colorways and imgSource.colorways as @Sameer says and you need initialize your obj imgSource
NOTE: use in .html
<pre>
{{cdkDropTarget.data|json}}
</pre>
To see the array that "store" the cdkDropList "target"
(*) e.g. in this stackblitz I used the a cdkDropList only to add elements to one array, in this another one drop elements in a CdkDropList to a group of cdkDropList who "data" is an object