Angular 2指令:对方法或属性访问的意外调用

时间:2017-03-08 13:53:19

标签: angular internet-explorer drag-and-drop draggable angular2-directives

我正在关注CryptoFileLoader class示例,以在Angular 2 cli项目上实现拖放功能。一切正常在Chrome上运行。在IE 11上,虽然我开始拖动元素时遇到异常。

this

有关如何解决此问题的任何建议?

1 个答案:

答案 0 :(得分:2)

这似乎是Internet Explorer的known bug,因为调用dataTransfer.setData除了“文本”之外的其他内容。不幸的是,这个例子正是如此,并且在IE中失败了。我已经实现了一种不同的方法 - 使用Angular服务来跟踪当前区域。这是更新的Plunkr

import { Injectable } from '@angular/core';

@Injectable()
export class DragService {
  private zone: string;

  startDrag(zone: string) {
    this.zone = zone;
  }

  accepts(zone: string): boolean {
    return zone == this.zone;
  }
}

可拖动

@Directive({
  selector: '[myDraggable]'
})
export class DraggableDirective {
  constructor(private dragService: DragService) {

  }

  @HostBinding('draggable')
  get draggable() {
    return true;
  }

  @Input()
  set myDraggable(options: DraggableOptions) {
    if (options) {
      this.options = options;
    }
  }

  private options: DraggableOptions = {};

  @HostListener('dragstart', ['$event'])
  onDragStart(event) {
    const { zone = 'zone', data = {} } = this.options;

    this.dragService.startDrag(zone);

    event.dataTransfer.setData('Text', JSON.stringify(data));
  }
}

放弃目标

@Directive({
  selector: '[myDropTarget]'
})
export class DropTargetDirective {
  constructor(private dragService: DragService) {

  }

  @Input()
  set myDropTarget(options: DropTargetOptions) {
    if (options) {
      this.options = options;
    }
  }

  @Output('myDrop') drop = new EventEmitter();

  private options: DropTargetOptions = {};

  @HostListener('dragenter', ['$event'])
  @HostListener('dragover', ['$event'])
  onDragOver(event) {
    const { zone = 'zone' } = this.options;

    if (this.dragService.accepts(zone)) {
       event.preventDefault();
    }
  }

  @HostListener('drop', ['$event'])
  onDrop(event) {
    const data =  JSON.parse(event.dataTransfer.getData('Text'));

    this.drop.next(data);
  }
}