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?
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.
In summary, scrollTop is how much it's currently scrolled, and scrollHeight is the total height, including content scrolled out of view.
store the position in cookies and after that use the cookie to scroll the page to exact position .
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With