Developer
Developer

Reputation: 289

Get the position in Angular like the jQuery position method

In jQuery we had the position() method:

$("button").click(function(){
    var x = $("p").position();
    alert("Top: " + x.top + " Left: " + x.left);
});

It will return the position of an element. How can I do the same in Angular?

Upvotes: 0

Views: 502

Answers (3)

Nazmul Hossain Rakib
Nazmul Hossain Rakib

Reputation: 51

The answer from "Sidy Mbengue" should be selected as the solved answer. It is simple and works exactly like the jquery position() method.

To get top:

document.querySelector('p').offsetTop 

To get left:

document.querySelector('p').offsetTop 

Upvotes: 0

Ryan Huang
Ryan Huang

Reputation: 726

Please try:

In component.html, define reference to html tag:

<p #position>I want to go back here</p>

In component.ts:

@ViewChild('position') HoldPosition: ElementRef;

clickFunction() {
  console.log(this.HoldPosition.nativeElement.offsetTop);
  console.log(this.HoldPosition.nativeElement.offsetLeft);

}

```

Upvotes: 1

Sidy Mbengue
Sidy Mbengue

Reputation: 19

document.querySelector('p').offsetTop 

This retrieves its top position relative to its parent, and offsetLeft relative to the left corner.

Upvotes: 1

Related Questions