Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2: Get position of HTML element

I'm trying to implement a custom directive in Angular 2 for moving an arbitrary HTML element around. So far everything is working except that I don't now how to get the initial position of the HTML element when I click on it and want to start moving. I'm binding to the top and left styles of my HTML element with those two host bindings:

/** current Y position of the native element. */
@HostBinding('style.top.px') public positionTop: number;

/** current X position of the native element. */
@HostBinding('style.left.px') protected positionLeft: number;

The problem is that both of them are undefined at the beginning. I can only update the values which will also update the HTML element but I cannot read it? Is that suppose to be that way? And if yes what alternative do I have to retrieve the current position of the HTML element.

like image 865
tzwickl Avatar asked Mar 03 '17 10:03

tzwickl


2 Answers

<div (click)="move()">xxx</div>
// get the host element
constructor(elRef:ElementRef) {}

move(ref: ElementRef) {
  console.log(this.elRef.nativeElement.offsetLeft);
}

See also https://stackoverflow.com/a/39149560/217408

like image 133
Günter Zöchbauer Avatar answered Sep 28 '22 19:09

Günter Zöchbauer


In typeScript you can get the position as follows:

@ViewChild('ElementRefName') element: ElementRef;

const {x, y} = this.element.nativeElement.getBoundingClientRect();
like image 40
William Perez Herrera Avatar answered Sep 28 '22 19:09

William Perez Herrera