I use Renderer2 to select the element that you want to play with also you can pass the class name as it is and the rest of uses are quite similar to other typescript classes. Lets say the first example of interactjs, put this chunk of html into your component template
<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>
And inside your component
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);
}
}
I don't think we need any other service layer to use this!