'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.
Solution 1:[1]
<div (click)="move()">xxx</div>
// get the host element
constructor(elRef:ElementRef) {}
move(ref: ElementRef) {
console.log(this.elRef.nativeElement.offsetLeft);
}
Solution 2:[2]
In typeScript you can get the position as follows:
@ViewChild('ElementRefName') element: ElementRef;
const {x, y} = this.element.nativeElement.getBoundingClientRect();
Solution 3:[3]
in html:
<div (click)="getPosition($event)">xxx</div>
in typescript:
getPosition(event){
let offsetLeft = 0;
let offsetTop = 0;
let el = event.srcElement;
while(el){
offsetLeft += el.offsetLeft;
offsetTop += el.offsetTop;
el = el.parentElement;
}
return { offsetTop:offsetTop , offsetLeft:offsetLeft }
}
Solution 4:[4]
You can use two way
// html
<div id="section" ></div>
// 1)
@ViewChild('section', { static: false }) public section?: ElementRef;
this.section.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
// 2)
document.getElementById("section").scrollIntoView({ behavior: "smooth", block: "center" });
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | William Perez Herrera |
Solution 3 | mohammad ali |
Solution 4 |