Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Directive, ElementRef, HostListener, Input} from "@angular/core";
- import {Position} from "../Interfaces/Position";
- @Directive({
- selector: '[movable]',
- host: {
- '(mousedown)': 'onMouseDown()',
- '(mousemove)': 'onMouseMove()',
- '(mouseup)': 'onMouseUp()'
- }
- })
- export class MovableDirective {
- @Input('movable') public elemToMove: ElementRef;
- public canMove : boolean = false;
- public currentElementPosition : Position = { x: 0, y: 0 };
- public currentMousePosition : Position = { x: 0, y: 0 };
- constructor(private elementRef: ElementRef) {}
- @HostListener('mousedown', ['$event'])
- /**
- * @param event {any} The event.
- */
- public onMouseDown(event: any) : boolean {
- let el = this.elemToMove ? this.elemToMove : this.elementRef;
- this.canMove = true;
- this.currentMousePosition = {
- x: event.pageX,
- y: event.pageY
- };
- this.currentElementPosition = {
- x: this.currentMousePosition.x - el.nativeElement.offsetLeft,
- y: this.currentMousePosition.y - el.nativeElement.offsetTop
- };
- return false;
- }
- @HostListener('mousemove', ['$event'])
- /**
- * @param event {any} The event.
- */
- public onMouseMove(event: any) : void {
- let el = this.elemToMove ? this.elemToMove : this.elementRef;
- if (this.canMove) {
- this.currentMousePosition.x = event.pageX;
- this.currentMousePosition.y = event.pageY;
- el.nativeElement.style.left = (this.currentMousePosition.x - this.currentElementPosition.x) + "px";
- el.nativeElement.style.top = (this.currentMousePosition.y - this.currentElementPosition.y) + "px";
- }
- }
- @HostListener('mouseup', ['$event'])
- /**
- * @param event {any} The event.
- */
- public onMouseUp(event: any) : void {
- this.canMove = false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement