When working with Angular CDK Drag & Drop, I am building a straightforward dashboard that includes a left sidebar and main content area. Both sections will contain unique custom components that should be draggable, reorderable within their respective areas, and transferable to other areas.
For example, if the Sidebar contains Comp
and Comp1
, I want to be able to rearrange them within the Sidebar and move them to the Main Content area.
As far as I know, Angular Material CDK Drag & Drop is designed for lists and requires items in those lists to be of the same type in order to be reordered or transferred.
Is there a way to use CDKDrag
and CDKDropList
for static items rather than items stored in an array? I am facing issues trying to reorder or transfer custom components to different drop zones.
I have prepared a sample project: https://stackblitz.com/edit/ng-mat-dnd Demo:
app.component.html
<div class="example-container">
<h2>Sidebar</h2>
<div cdkDropList #sidebarList="cdkDropList" [cdkDropListData]="sidebar" cdkDropListConnectedTo="[mainList]"
class="example-list" (cdkDropListDropped)="drop($event)">
<div class="example-box" cdkDrag>
<app-demo-comp-2 [btn]=2></app-demo-comp-2>
</div>
<div class="example-box" cdkDrag>
<app-demo-comp [ddn]=2></app-demo-comp>
</div>
<div class="example-box" cdkDrag>
<app-demo-comp-3 [txt]=3></app-demo-comp-3>
</div>
</div>
</div>
<div class="example-container">
<h2>Main</h2>
<div cdkDropList #mainList="cdkDropList" [cdkDropListData]="main" cdkDropListConnectedTo="[sidebarList]"
class="example-list" (cdkDropListDropped)="drop($event)">
<div class="example-box" cdkDrag>
<app-demo-comp [ddn]=1></app-demo-comp>
</div>
<div class="example-box" cdkDrag>
<app-demo-comp-2 [btn]=3></app-demo-comp-2>
</div>
</div>
</div>
app.component.ts
import { Component, OnInit, ViewChildren, QueryList } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem, CdkDrag } from '@angular/cdk/drag-drop';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
sidebar;
main;
@ViewChildren(CdkDrag) draggables: QueryList<CdkDrag>;
constructor() { }
ngOnInit() { }
ngAfterViewInit() {
console.log(this);
this.sidebar = [this.draggables.toArray()[0], this.draggables.toArray()[1], this.draggables.toArray()[2]];
console.log(this.sidebar);
this.main = [this.draggables.toArray()[4], this.draggables.toArray()[3]];
console.log(this.main);
}
drop(event: CdkDragDrop<any[]>) {
console.log(event);
if (event.previousContainer === event.container) {
console.log('Same container');
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
console.log('Different containers');
transferArrayItem(event.previousContainer.data,
event.container.data,
event.previousIndex,
event.currentIndex);
}
}
}