Reputation: 488
I'm trying to implement a drag and drop list in Angular using the Angular CDK. The list should have parent and child elements, and I want to enable the ability to drag and drop both parent items and their child items. Additionally, I need to allow dragging child items within their respective parent container.
I have already set up the basic structure of the list and implemented the drag and drop functionality, but I'm facing issues with dragging child items between parent container. When I try to drag and drop the child between different parents I am not able to do that. How can I acheive this?
Below is the stackblitz link: https://stackblitz.com/edit/angular-dragdrop-from-parent-to-nested-childlist-p943w3?file=app%2Fcdk-drag-drop-connected-sorting-example.html,app%2Fcdk-drag-drop-connected-sorting-example.css,app%2Fcdk-drag-drop-connected-sorting-example.ts
Here's my current implementation:
<div cdkDropListGroup>
<ul
cdkDropList
[cdkDropListData]="parent"
[cdkDropListConnectedTo]="parentIds"
class="example-list"
(cdkDropListDropped)="drop($event)"
>
<li *ngFor="let item of parent" cdkDrag [cdkDragData]="parent">
{{item.name}}
<ul
#childList="cdkDropList"
*ngIf="item.children"
[cdkDropListData]="item.children"
cdkDropList
[cdkDropListConnectedTo]="[parent1]"
(cdkDropListDropped)="drop($event)"
>
<li
*ngFor="let subItem of item.children"
cdkDrag
[cdkDragData]="item.name"
>
{{subItem.name}}
</li>
</ul>
</li>
</ul>
</div>
component.ts
parentList: any[] = [
{ id: 1, name: 'Parent 1', children: [{ id: 11, name: 'Child 1' }, { id: 12, name: 'Child 2' }] },
{ id: 2, name: 'Parent 2', children: [{ id: 21, name: 'Child 3' }, { id: 22, name: 'Child 4' }] }
];
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,
event.previousIndex,
event.currentIndex
);
}
}
}
ave also applied CSS styles to ensure proper visual representation of the parent and child items.
I would appreciate any guidance on how to correctly implement the drag and drop functionality for the child items within the parent container. What changes do I need to make to my code to achieve this behavior?
Upvotes: 0
Views: 1488
Reputation: 738
I was able to get this to work by removing the [cdkDropListConnectedTo]="parentIds"
in the template.
Upvotes: 0