Angular: Scroll Dynamic Element Into View Knowing Only Its ID


Answer :

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>


This is not strictly angular, but you could do document.querySelector('#MyList31').scrollIntoView().

Reference https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

For doing this strictly angular, this article may help you http://www.benlesh.com/2013/02/angular-js-scrolling-to-element-by-id.html


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?