我目前正在使用 Angular 2 和来自 https://material.angular.io/cdk/drag-drop/overview 的拖放模块.我已经使拖放功能起作用。我有两种不同类型的类对象,我希望将它们限制在它们自己的拖放列表类型中。
这很可能通过对列表进行分组来解决,但是由于我使用递归,其他问题出现了......
目前我将每个列表都放在同一个组中,这意味着可以在每个列表中拖放任何内容(cdkDropListGroup,在执行递归部分之前位于组件中)。
我试图将列表限制为仅接受元素或属性(但不能同时接受两者),但我不知道该怎么做...
我有以下内容:
类:
export class Attribute {
name: string;
type: string;
}
export class Element {
id: number;
name: string;
elements: Element[]
attributes: Attribute[];
}
HTML:
<div >
Elements
<div
cdkDropList
[cdkDropListData]="elements"
class="example-list"
(cdkDropListDropped)="drop($event)"
[cdkDropListEnterPredicate]="isElement">
<div type="button" text-align="right" class="btn btnNotInline" (click)="addNewElement()">
<img src="assets/img/IconPlus.png" class="elementListIcon"></div>
<div *ngFor="let element of elements" class="example-box" cdkDrag>
<mat-list>
<mat-list-item>
<mat-form-field appearance="standard dense" class="example-container">
<input matInput placeholder="{{element.name}}">
</mat-form-field>
</mat-list-item>
<mat-list-item>
<div
cdkDropList
[cdkDropListData]="attributes"
class="cdk-drag-list-attributes"
(cdkDropListDropped)="drop($event)"
[cdkDropListEnterPredicate]="isAttribute">
<div type="button" text-align="right" class="btn btnNotInline" (click)="addNewAttribute()">
<img src="assets/img/IconPlusPurple.png" class="elementListIcon"></div>
<div *ngFor="let attribute of attributes" class="example-container" cdkDrag>
<p class="mat-input-element-attribute">
<input matInput placeholder="{{attribute.name}}">
<input matInput placeholder="{{attribute.type}}">
</p>
</div>
</div>
</mat-list-item>
<mat-list-item>
<app-listboardelement [attributes]="element.attributes" [elements]="element.elements"></app-listboardelement>
</mat-list-item>
</mat-list>
</div>
被调用的方法(属性看起来很像)
isElement(drag : CdkDrag){
console.log("check " + (drag instanceof Element) + typeof drag + " , "+ typeof drag.data + ", "+ drag.data + " , " +(drag.data instanceof Element));
return (drag.data instanceof Element);
}
从输出中我简单地得到:“check false object,undefined,undefined,false” 由此我尝试将拖动的对象与类进行比较..但我没有任何运气。
有什么方法可以动态地将拖动的对象限制在某些列表中吗?我知道 [cdkDropListConnectedTo] 但这给了我发生递归和绑定(bind)的问题。任何指导将不胜感激
最佳答案
您始终可以检查拖放“起点到终点”容器并采取相应的行动,例如:
drop(event: CdkDragDrop<string[]>) {
// same container (just reorder items)
if (event.previousContainer === event.container) {
moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
} else {
// from first list to second list
if (event.previousContainer.id === 'cdk-drop-list-0' && event.container.id === 'cdk-drop-list-1') {
// do something
}
// from second list to first list
if (event.previousContainer.id === 'cdk-drop-list-1' && event.container.id === 'cdk-drop-list-0') {
// do something
}
}
}
希望这对您有所帮助!
关于javascript - Angular cdkDropList 拖动元素限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53468815/