Angular2上的Interact.js与DefinitelyTyped

时间:2016-06-06 10:42:56

标签: angular definitelytyped interact.js

我在我的项目中安装了interact.js angular2,但我不知道如何使用文档中描述的方法。

我的导入如下

import * as _ from 'interact';

Angular2中是否有可能提供全面服务interact.js?如何创建拖放支持?

DT https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/interact.js

1 个答案:

答案 0 :(得分:1)

我使用Renderer2来选择要播放的元素,也可以按原样传递类名,其余的用法与其他的typescript类非常相似。让我们说第一个interactjs的例子,把这个html块放到你的组件模板中

  <div id="drag-1" class="draggable">
    <p> You can drag one element </p>
  </div>
  <div id="drag-2" class="draggable">
    <p> with each pointer </p>
  </div>

在您的组件内

import { Component, OnInit, Renderer2 } from '@angular/core';
import * as interact from 'interactjs';

@Component({
  selector: 'app-playground',
  templateUrl: './playground.component.html',
  styleUrls: ['./playground.component.css']
})
export class PlaygroundComponent implements OnInit {

  constructor(private renderer2: Renderer2) { }

  ngOnInit() {
    const draggableEl = this.renderer2.selectRootElement('.draggable');

    // target elements with the "draggable" class
    interact(draggableEl)
      .draggable({
        // enable inertial throwing
        inertia: true,
        // keep the element within the area of it's parent
        restrict: {
          restriction: 'parent',
          endOnly: true,
          elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
        },
        // enable autoScroll
        autoScroll: true,

        // call this function on every dragmove event
        onmove: this.dragMoveListener,
        // call this function on every dragend event
        onend: function (event) {
          const textEl = event.target.querySelector('p');

          textEl && (textEl.textContent =
            'moved a distance of '
            + (Math.sqrt(Math.pow(event.pageX - event.x0, 2) +
              Math.pow(event.pageY - event.y0, 2) | 0))
              .toFixed(2) + 'px');
        }
      });
  }

  private dragMoveListener(event) {
    const target = event.target,
      // keep the dragged position in the data-x/data-y attributes
      x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
      y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;

    // translate the element
    target.style.webkitTransform =
      target.style.transform =
      'translate(' + x + 'px, ' + y + 'px)';

    // update the posiion attributes
    target.setAttribute('data-x', x);
    target.setAttribute('data-y', y);
  }

}

我认为我们不需要任何其他服务层来使用它!