如果您的拖放解决方案是基于 HTML5 的,也许您可以使用来自 '@angular/core' 的 HostListener 装饰器来破解您的拖放交换逻辑:
在放置区域组件上添加类似这样的内容:
@HostListener('drop', ['$event'])
onDrop(event: any) {
//do something
}
在您的可拖动组件上是这样的:
@HostListener('dragstart', ['$event'])
onDrag(event: any) {
//do something
}
HostListeners 为您提供了为 onmousedown、onkeyup、ondrop、ondrag 等元素事件实现常规侦听器的方法。
然后考虑一些逻辑来识别正在拖放的内容并更改拖动区域组件模型。这是我受 W3Schools 关于拖放主题的启发而制作的一些功能代码:
import { Component, HostListener, Input } from '@angular/core';
// The draggable component
@Component({
selector: 'dragme',
template: `
<div draggable="true">
Drag {{name}}!
</div>
`,
styles: [`
[draggable] {
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
user-select: none;
-khtml-user-drag: element;
-webkit-user-drag: element;
background-color: #AAA;
border: 1px solid black;
padding: 24px;
margin: 12px;
}
`]
})
export class DragMe {
@Input()
name:string = "";
@HostListener('dragstart', ['$event'])
onDrag(event:any){
event.dataTransfer.setData("name",this.name);
}
}
// The drop area component
@Component({
selector: 'drop',
template: `
<div class="drop">
Drop over me!
<ul>
<li *ngFor="let i of items">{{i}}</li>
</ul>
</div>
`,
styles: [`
.drop{
border: 1px solid black;
padding: 24px;
}
`]
})
export class DropOverMe {
items:string[] = [];
@HostListener('dragover', ['$event'])
onDragover(event:any){
event.preventDefault();
}
@HostListener('drop', ['$event'])
onDrop(event:any){
event.preventDefault();
var name = event.dataTransfer.getData("name");
this.items.push(name);
}
}
// The functional example
@Component({
selector: "drag-example",
template: `
<dragme name="Bob"></dragme>
<dragme name="Alice"></dragme>
<dragme name="Carl"></dragme>
<drop></drop>
`
})
export class DragExample{
}
完整代码在:https ://github.com/rafaelodon/angular2-html5-dragndrop-example