Angular2 拖放目标

Angular2 Drag and Drop Target

我在我的 angular2 应用程序中实现了一个拖放功能,它的工作原理是这样的...用户会看到他们可以从中选择的选项列表和列表上方的放置区 - 当他们从一个选项中拖动时将选项放入拖放区,然后处理事件。

到目前为止,我有一个 draggable 指令,它处理拖动开始事件并在该事件的 dataTransfer 属性上设置一些数据。我试图做的是制作另一个指令,它是一个 dropTarget 指令,它只处理放置事件并获取数据。

这是可以做到的吗?对于可拖动的 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]
})

以为我会来完成这个问题 - 我使用了错误的事件处理函数 - 试图从 dragover 事件中获取数据是我不打算做的事情。

ondrop 函数是正确的使用方式,并且完全符合我的预期。