Search code examples
angularangular2-directives

Angular 2 create Directive for dragging elements


I'm trying to create a Dicrective in Angular 2 that allows the user to drag the HTML Element by the x position.
I wrote this pseudo code of how I think it might work, but am not experienced enough with directives to know what the right HostListener parameter would be.

import { Directive, ElementRef, Renderer, HostListener } from '@angular/core';


@Directive({
    selector: '[draggable]'
})

export class DragDirective {

    constructor(private el: ElementRef, private renderer: Renderer) { }

    @HostListener('move')
    moveElement(xpos:number) {
        this.renderer.setElementProperty(this.el.nativeElement, 'xpos', xpos);
    }
}

More specifically I'm trying to use this to move Tabs from Angular 2 Material for with I would also have to update its index.


Solution

  • Ok i did it using jQuery ui's sortable function.

    import { Directive } from '@angular/core';
    
    
    @Directive({
        selector: '[draggable]'
    })
    
    export class DragDirective {
    
        constructor() {
            $(function() {
                (<any>$("#sortable-tabs")).sortable();
            });
        }
    }
    

    The (< any >$("#sortable-tabs")) is there because otherwise it would throw an error while compiling that the sortable function is not defined