cedvdb / ng2draggable

draggable directive for angular 2
https://cedvdb.github.io/ng2draggable/
MIT License
18 stars 16 forks source link

Element draggable outside of parent element #13

Open ProfessorBleedy opened 7 years ago

ProfessorBleedy commented 7 years ago

I'm using this plugin for a project and it's great. Only issue i'm having right now though is that the window can be dragged off to the side of it's parent. so you can actually lose the window off screen. Is there a way to force the draggable window to be bound to the visible area of it's parent?

I've attached an example using your demo.

draggable-offscreen

devrockzz commented 7 years ago

Hi i am also facing the same problem it is going outside the parent element any solution will help otherwise it awesome

ProfessorBleedy commented 7 years ago

@devrockzz , I was able to fix it on my end by pulling the draggable.directive.ts into my own code base, making it a local directive and then modifying it with an ElementRef Input variable of a container the window should be bound by. Now for me at least, the window will always remain within the confines of the specified element.

devrockzz commented 7 years ago

@ProfessorBleedy , Thanks for the info actually i am new to the ng2 so if you can share a demo it will be great !!! so i am counting on you bro ..........

Omikhleia commented 7 years ago

@devrockzz Would you mind sharing (or even better, suggesting a pull request to the package maintainer)?

vbunjes commented 7 years ago

@Omikhleia @ProfessorBleedy

I had the same problem so I moved the directive into my codebase

Implemented AfterViewInit to the AngularDraggableDirective class

export class AngularDraggableDirective implements OnInit, AfterViewInit {
   private parent:HTMLElement;

Added the required function

ngAfterViewInit() {
        const hostElem = this.el.nativeElement;
        this.parent = hostElem.parentNode;
 }
private moveTo(x: number, y: number) {
    if (this.orignal) {

        let parentWidth = this.parent.clientWidth;
        let parentHeight = this.parent.clientHeight;

        let left = x - this.orignal.x;
        let top = y - this.orignal.y;
        let maxLeft = parentWidth - this.el.nativeElement.clientWidth;
        let maxTop = parentHeight - this.el.nativeElement.clientHeight;

        if (left < 0) {
            left = 0;
        }

        if (left > maxLeft) {
            left = maxLeft;
        }

        if (top < 0) {
            top = 0;
        }

        if (top > maxTop) {
            top = maxTop;
        }
        this.renderer.setElementStyle(this.el.nativeElement, 'left', `${left}px`);
        this.renderer.setElementStyle(this.el.nativeElement, 'top', `${top}px`);
    }
}
Omikhleia commented 7 years ago

Thanks !