由于某些原因(阅读:无法创建许多组件),我必须在我的应用程序上创建可以用作放置元素的部分。 (无法使用*ngIf
)
我创建了DropListRef,例如-
constructor(private dragDropService: DragDrop) {}
const dropListRef = this.dragDropService
.createDropList(dropZone)
.withItems([]);
并且我正在尝试检测是否已将元素删除为-
dropListRef.dropped.subscribe(event => {
console.log("dropped: ");
});
但是,我从未找到控制台输出。
链接到示例代码-https://stackblitz.com/edit/angular-r3spyc
链接到演示视频-https://drive.google.com/file/d/1b6RUuOk9r7s9vFd3NlhgR9ot1hHP1Oeb/view
无法创建很多组件
dropped
,entered
之类的事件。感觉到我缺少一些重要的步骤,例如在某个地方注册或与其他DropList连接,然后Angular Material可以识别或识别它。Dropbox component
),是因为这会简化当前的问题。与问题相关的复杂性太多,无法封装在单个组件中,例如Dropbox component
(或很多)。如果我按照每个用例创建模板的路线,最终可能会创建100多个ng-templates(或不同的组件)。您的编码方式不是Angular的典型编码方式。我抬起Angular official site并为您做了一些调整。
我用drop-box.component.html创建了一个保管箱组件:
<div>{{text}}</div>
drop-box.component.ts:
import { Component, Input } from "@angular/core";
@Component({
selector: "drop-box",
templateUrl: "./drop-box.component.html",
styleUrls: ["./drop-box.component.scss"]
})
export class DropboxComponent {
@Input() text = "";
constructor() {}
}
对于您的app.component.ts:
import { Component } from "@angular/core";
import {
CdkDragDrop,
CdkDrag,
DragDropRegistry,
DragDrop,
DragRef,
moveItemInArray,
transferArrayItem
} from "@angular/cdk/drag-drop";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.scss"]
})
export class AppComponent {
title = "angular-draggable";
previousIndex = 0;
todo = ["a", "b", "c", "d", "e"];
list = ["default item"];
isEnabled = false;
constructor(private dragDropService: DragDrop) {}
onDragStart(event, i) {
console.log("drag started!", event);
console.log('event.previousIndex',event.previousIndex);
console.log('i',i);
this.previousIndex = i;
}
createDroplist() {
this.isEnabled = !this.isEnabled;
}
drop(event: CdkDragDrop<string[]>){
if(this.isEnabled)
{
transferArrayItem(event.previousContainer.data,
event.container.data,
this.previousIndex,
event.currentIndex);
}
}
}
注意可能不再需要“单击我创建下拉列表”按钮和createDroplist方法。但是我将其放在此处以启用/禁用拖动,以防您仍然需要它。
和app.component.html:
<div cdkDropListGroup>
<div class="example-container">
<h2>To do</h2>
<div style="position: relative;">
<ng-container *ngFor="let item of todo; let i = index">
<div cdkDropList #todoList="cdkDropList" class="example-list" [cdkDropListData]="todo" [cdkDropListConnectedTo]="[doneList]">
<div class="example-box stupid">{{item}}</div>
<div class="example-box" (cdkDragStarted)="onDragStart($event, i)" cdkDrag>{{item}}</div>
</div>
</ng-container>
</div>
</div>
<button (click)="createDroplist()">
Click me to create droplist
</button>
<div id='box' cdkDropList
#doneList="cdkDropList"
[cdkDropListData]="list"
[cdkDropListConnectedTo]="[todoList]"
(cdkDropListDropped)="drop($event)">
<div *ngFor="let item of list">
<drop-box [text]="item"></drop-box>
</div>
</div>
</div>
您可以查看我的示例here。 再次,要从待办事项列表中拖动,您现在需要先单击“单击我创建下拉列表”按钮,然后拖放。
快乐编码!