Angular2 拖放目标

pep*_*ght 5 drag-and-drop directive typescript angular

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

到目前为止,我有一个可拖动指令来处理拖动开始事件并在该事件的 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');
    }

}
Run Code Online (Sandbox Code Playgroud)

这是拖动目标指令代码:

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'));
    }

}
Run Code Online (Sandbox Code Playgroud)

最后这里是包含这两个指令的 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>
Run Code Online (Sandbox Code Playgroud)

我还有组件的元数据,其中包含在此处导入和声明的指令

import {DraggableDirective, DragTargetDirective} from '../draggable';

@Component({
    templateUrl: 'app/dashboard/dashboard.component.html',
    styleUrls: [require('./dashboard.component.scss')],
    directives: [DraggableDirective, DragTargetDirective]
})
Run Code Online (Sandbox Code Playgroud)

pep*_*ght 3

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

ondrop 函数是正确的使用方法,并且完全按照我的预期工作。