Advertisement
Guest User

Untitled

a guest
Dec 3rd, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. import {Directive, ElementRef, HostListener, Input} from "@angular/core";
  2. import {Position} from "../Interfaces/Position";
  3.  
  4. @Directive({
  5. selector: '[movable]',
  6. host: {
  7. '(mousedown)': 'onMouseDown()',
  8. '(mousemove)': 'onMouseMove()',
  9. '(mouseup)': 'onMouseUp()'
  10. }
  11. })
  12. export class MovableDirective {
  13. @Input('movable') public elemToMove: ElementRef;
  14.  
  15. public canMove : boolean = false;
  16. public currentElementPosition : Position = { x: 0, y: 0 };
  17. public currentMousePosition : Position = { x: 0, y: 0 };
  18.  
  19. constructor(private elementRef: ElementRef) {}
  20.  
  21. @HostListener('mousedown', ['$event'])
  22. /**
  23. * @param event {any} The event.
  24. */
  25. public onMouseDown(event: any) : boolean {
  26.  
  27. let el = this.elemToMove ? this.elemToMove : this.elementRef;
  28.  
  29. this.canMove = true;
  30. this.currentMousePosition = {
  31. x: event.pageX,
  32. y: event.pageY
  33. };
  34. this.currentElementPosition = {
  35. x: this.currentMousePosition.x - el.nativeElement.offsetLeft,
  36. y: this.currentMousePosition.y - el.nativeElement.offsetTop
  37. };
  38. return false;
  39. }
  40.  
  41. @HostListener('mousemove', ['$event'])
  42. /**
  43. * @param event {any} The event.
  44. */
  45. public onMouseMove(event: any) : void {
  46.  
  47. let el = this.elemToMove ? this.elemToMove : this.elementRef;
  48.  
  49. if (this.canMove) {
  50.  
  51. this.currentMousePosition.x = event.pageX;
  52. this.currentMousePosition.y = event.pageY;
  53.  
  54. el.nativeElement.style.left = (this.currentMousePosition.x - this.currentElementPosition.x) + "px";
  55. el.nativeElement.style.top = (this.currentMousePosition.y - this.currentElementPosition.y) + "px";
  56. }
  57. }
  58.  
  59. @HostListener('mouseup', ['$event'])
  60. /**
  61. * @param event {any} The event.
  62. */
  63. public onMouseUp(event: any) : void {
  64. this.canMove = false;
  65. }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement