关于 Angular CDK 的拖放功能,我正在尝试创建一个简单的仪表板,其中包括左侧边栏和主内容区。这两个区域都将包含独特的自定义组件,这些组件需要可拖动,并可以在其所包含的区域内重新排序并转移到另一个区域。
例如,边栏包含 Comp 和 Comp1,则可以在该区域内重新排序它们并将它们转移到主内容区。
据我所知,Angular Material CDK 拖放功能仅适用于列表。此外,列表中的项目必须是类似类型,以便它们可以被重新排序/转移。
有没有一种方法可以利用CDKDrag和CDKDropList来处理静态项而不是数组中的项?我无法重新排序或将自定义组件传输到不同的文件夹列表中。
我已经创建了一个示例项目:https://stackblitz.com/edit/ng-mat-dnd 演示: https://ng-mat-dnd.stackblitz.io/ app.component.html
例如,边栏包含 Comp 和 Comp1,则可以在该区域内重新排序它们并将它们转移到主内容区。
据我所知,Angular Material CDK 拖放功能仅适用于列表。此外,列表中的项目必须是类似类型,以便它们可以被重新排序/转移。
有没有一种方法可以利用CDKDrag和CDKDropList来处理静态项而不是数组中的项?我无法重新排序或将自定义组件传输到不同的文件夹列表中。
我已经创建了一个示例项目:https://stackblitz.com/edit/ng-mat-dnd 演示: 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);
}
}
}