With reference to Angular CDK Drag & Drop, I'm trying to create a simple dashboard with left sidebar and main content area. Both of these areas will contain unique custom components which need to be draggable and can be reordered within their contained area and transferred to another area.
For eg. Sidebar contains Comp
and Comp1
, then I can reorder them within that area and transfer them to the Main Content area.
From what I understand Angular Material CDK Drag & Drop only works with lists. Additionally, the items in the lists have to be of a similar type for them to be reordered/transferred.
Is there a way to utilize CDKDrag
and CDKDropList
for static items rather than items in an array? I'm not able to reorder or transfer custom components to different drop lists.
I've created a sample project: https://stackblitz.com/edit/ng-mat-dnd Demo: https://ng-mat-dnd.stackblitz.io/
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);
}
}
}