【发布时间】:2020-11-04 06:52:07
【问题描述】:
参考 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
<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);
}
}
}
【问题讨论】:
标签: angular typescript angular-material drag-and-drop