2

I have div element on the page:

<div #draggable></div>

@ViewChild('draggable') private draggableElement: ElementRef;

I listen scroll event and try change position of this block:

@HostListener('window:scroll', ['$event']) onScrollEvent($event){
    this.draggableElement.nativeElement.clientTop = 200;
  }

But it does not work!

POV
  • 11,293
  • 34
  • 107
  • 201

1 Answers1

6

If the element has an absolute position, you can set the left and top style attributes:

this.draggableElement.nativeElement.style.left = "100px";
this.draggableElement.nativeElement.style.top = "200px";

An alternative is to move it with a CSS transform:

this.draggableElement.nativeElement.style.transform = "translateX(100px)";
this.draggableElement.nativeElement.style.transform = "translateY(200px)";
this.draggableElement.nativeElement.style.transform = "translate(100px, 200px)";
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • Thank you, how to get coordinates of window from `$event`? – POV Aug 21 '18 at 20:02
  • 2
    You can take a look at [this question](https://stackoverflow.com/q/3464876/1009922). – ConnorsFan Aug 21 '18 at 20:07
  • [This post](https://stackoverflow.com/q/442404/1009922) gives various techniques to get the position of an element (if that is what you meant by the "window"). You can also retrieve the current values of the `left` and `top` style attributes of the element. – ConnorsFan Aug 21 '18 at 20:15
  • And [this stackblitz](https://stackblitz.com/edit/angular-8cyr2p) uses `window.scrollX` and `window.scrollY` to get the scroll position. – ConnorsFan Aug 21 '18 at 20:26