【发布时间】:2016-08-31 03:57:18
【问题描述】:
我在我的 angular2 应用程序中实现了一个拖放功能,它的工作原理是这样的......用户会看到一个他们可以从中选择的选项列表以及列表上方的一个放置区 - 当他们从其中一个拖动时将选项放入拖放区,然后处理事件。
到目前为止,我有一个可拖动的指令来处理拖动开始事件并在事件的 dataTransfer 属性上设置一些数据。我试图做的是创建另一个指令,它是一个 dropTarget 指令,它只处理 drop 事件并抓取数据。
这是可以做到的吗?对可拖动的 div 和放置区域使用相同的指令并插入一些逻辑以仅在将 div 放置在正确的目标上时才允许放置事件发生,我会更好吗?
谢谢
编辑:代码
这是我的可拖动指令的代码:
import {Directive, ElementRef} from '@angular/core';
@Directive({
selector: '[myDraggable]',
host: {
'(dragstart)': 'onDragStart($event)',
'(dragover)': 'onDragOver($event)',
'(dragleave)': 'onDragLeave($event)',
'(dragenter)': 'onDragEnter($event)',
'(drop)': 'onDrop($event)'
}
})
export class DraggableDirective {
constructor(el: ElementRef) {
el.nativeElement.setAttribute('draggable', 'true');
}
onDragStart(ev: DragEvent) {
console.log("Drag Started");
ev.dataTransfer.setData('Text', 'Data from drag start');
}
}
这里是拖动目标指令代码:
import {Directive, ElementRef} from '@angular/core';
@Directive({
selector: '[dragTarget]',
host: {
'(dragover)': 'onDragOver($event)'
}
})
export class DragTargetDirective {
onDragOver(ev: DragEvent) {
console.log("dragged over target" + ev.dataTransfer.getData('Text'));
}
}
最后是包含两个指令的 html
<div class="relativeContainer">
<div class="absoluteBox" *ngFor="let process of processes" [ngClass]="{'active': process.active}">
<div class="process-title">{{process.stage}} - {{process.name}}</div>
<div dragTarget *ngIf="process.options" class="process-selection">{{process.options[process.selectedOption]}}</div>
<ul class="option-list">
<li myDraggable *ngFor="let option of process.options" class="option-item"><p>{{option}}</p></li>
</ul>
</div>
我还有组件的元数据,其中包含在此处导入和声明的指令
import {DraggableDirective, DragTargetDirective} from '../draggable';
@Component({
templateUrl: 'app/dashboard/dashboard.component.html',
styleUrls: [require('./dashboard.component.scss')],
directives: [DraggableDirective, DragTargetDirective]
})
【问题讨论】:
-
当然可以。您能否添加一些代码来演示您已经尝试过的内容。
-
好的,添加了我到目前为止的代码 - 基本上我想在拖动开始时在 draggableDirective 中设置一些数据并在 dragTargetDirective 中检索它
-
有什么问题?你卡在哪里了。是否调用了
dragover事件处理程序? -
是的,调用了拖动事件,但它似乎无法访问在另一个指令中设置的“文本”属性内的数据,comsole 日志在硬编码后什么也不打印字符串
-
好的,所以看起来 ev.dataTransfer 没有在拖动事件上返回文本,也许我读错了文档,它实际上不能这样做,但我是想要在 drop 事件上执行此操作 - 将 drop 事件放入,它现在正在工作。
标签: angular typescript drag-and-drop directive