Issue
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?
Solution
I managed to solve this using property binding.
First, when I receive the parameter that defines which item to scroll into, I save it as a component property.
this.toScrollInto = Object.keys(params)[0];
Then, inside of the ngFor that builds it, I bind into it and make use of short-circuiting to call a function if there is a match.
<div class="items" *ngFor="let item of functionThatGetsItems(); let i = index"
#itemRef
[class.scrolled]="i == this.toScrollInto && scrollIntoView(itemRef)">
<div class="title">
{{ item.title }}
</div>
<div class="content">
{{ item.content }}
</div>
</div>
The function scrollIntoView(Element)
then handles the scrolling using the provided Angular reference.
Answered By - Chris Jaquez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.