Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Scroll dynamic element into view knowing only its ID

I have a dynamic list that gets its data asynchronously, and would like to scroll an specific element into view when the list is loaded.

The list is build similar to this:

<div class="items" *ngFor="let item of functionThatGetsItems(); let i = index" [id]="'MyList' + i">
    <div class="title">
        {{ item.title }}
    </div>
    <div class="content">
        {{ item.content }}
    </div>
  </div>      

As you can see, the items have an ID assigned that is simple a base string and their number. Let's say I want to trigger a scroll to MyList31. Once the list is loaded and rendered, how do I fetch the element with such ID and scroll to it?

I've searched around and found the ways you should not do it, and how to do it using ViewRefs, but these don't seem to work on dynamic elements, or do they? How would I do this?

like image 241
Chris Jaquez Avatar asked Feb 27 '18 01:02

Chris Jaquez


People also ask

How do I scroll to a specific element?

The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.

What is scrollTop and scrollHeight?

In summary, scrollTop is how much it's currently scrolled, and scrollHeight is the total height, including content scrolled out of view.

How can I retain the scroll position of a scrollable area when pressing back button?

store the position in cookies and after that use the cookie to scroll the page to exact position .

What is scrollTop in angular?

ng-scrolltop demo: angular component that monitors current Y position in a long page or element then if scrolled down enough, shows up a clickable, unobtrusive icon that scrolls to top smoothly.


1 Answers

You want the id to be on the actual item that the ng-for creates, not the ng-for itself. That would eliminate the need for any extra logic when passing data to the list from the component.

// inside ngAfterViewInit() to make sure the list items render or inside ngAfterViewChecked() if you are anticipating live data using @Inputs
const itemToScrollTo = document.getElementById('item-' + id);
// null check to ensure that the element actually exists
if (itemToScrollTo) {
  itemToScrollTo.scrollIntoView(true);
}
<div class="list" *ngFor="let item of functionThatGetsItems(); let i = index">
  <div class="list-item" id="item-{{i}}">
    <div class="title">
        {{ item.title }}
    </div>
    <div class="content">
        {{ item.content }}
    </div>
  </div>
</div>
like image 186
areddicks1014 Avatar answered Sep 20 '22 14:09

areddicks1014