0

I am trying to convert an angular directive written in angular 1.* to angular 2.

Here is the original directive code:

this.directiveModule.directive('draggable', function(CONFIG) {
return {
  restrict: 'A',
  link: function(scope, elem, attrs) {
    var setInitPosition;
    setInitPosition = function() {
      return elem.css({
        top: scope.position.top + 'px',
        left: scope.position.left + 'px'
      });
    };
    elem.draggable({
      containment: "parent",
      stop: function(ev, ui) {
        return scope.position = {
          top: ui.position.top,
          left: ui.position.left
        };
      }
    });
    return setInitPosition();
  }
};

});

I have converted it to the angular 2 directive as follows:

@Directive(
{
    selector: "[draggable]"
}
) 
export class DraggableDirective implements OnInit{

@Input() position: any;
@Output() setPosition: EventEmitter<any> = new EventEmitter();  // assign position to scope.designElement

constructor(private elem: ElementRef){}

setInitPosition() {
    this.elem.nativeElement.css({
        top: this.position.top + 'px',
        left: this.position.left + 'px'
    });
};

ngOnInit(){
    this.elem.nativeElement.draggable({
        containment: "parent",
        stop: this.stopDrag
    });
    this.setInitPosition();
}

stopDrag(ev, ui){
    let position = {
        top: ui.position.top,
        left: ui.position.left
    };
    this.setPosition.emit(position);
}
}

But when I use this new directive on an element, i get an error saying elem.nativeElement does not contain draggable function at the following line in the ngOnInit() function.

this.elem.nativeElement.draggable({

How do I replace this call?

D M
  • 417
  • 1
  • 5
  • 9

2 Answers2

0

Since draggable and css are both jquery plugin functions, I included jquery variable and used it like this.

$(this.elem.nativeElement).draggable(...)

and

$(this.elem.nativeElement).css(...)

I declared the jquery $ variable like this

declare var $: any;
D M
  • 417
  • 1
  • 5
  • 9
0

tslint doesn't know anything about a member "draggable" of jQuery.

You need to add this property to the type definition at the end of /typings/jquery/jquery.d.ts

interface JQuery {
    draggable(options?:any):JQuery;
}

If you don't have jquery.d.ts, first you need to install jQuery definition for typescript

tsd install jquery --save

and include

/// <reference path="typings/jquery/jquery.d.ts" />

into your ts file.

This information is based on https://stackoverflow.com/a/30662773

Community
  • 1
  • 1
Andrei Zhytkevich
  • 8,039
  • 2
  • 31
  • 45