0

Could you tell me how manage the scrollToIndex (virtuall scroll) if my list is not loaded during the ngAfterViewInit lifehook? I need to call the scroll to the index when I m redirect from an other page, so in the ts file. So my goal is to point to the right index when the page is loaded

@ViewChild(CdkVirtualScrollViewport) viewport: CdkVirtualScrollViewport;
ngOnInit() {
...
this.getData(index);
}

getData(index){
return this.service.get().subscribe(data => {
this.fullDatasource = data;
this.selectedIndex = this.fullDatasource.findIndex(value => value.id === index);
}

ngAfterViewInit() {
this.viewport.scrollToIndex(this.selectedIndex);
}

Nothing happens, if I call the method in the ngAfterViewInit. Many many thnaks in advance.

0

2 Answers 2

2

You could try running the scrollToIndex in a setTimeout function, i think this triggers another round of change detection, by then your list could be loaded. Another way to archive this is to use the ChangeDetectorRef, see the official docs for details on how this works.

Or trigger the scroll manually in the subscription of the getData method instead of AfterViewInit.

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks Johannes, it does work with a set timeout in the getData but I feel like I'm doing something wrong. Will it work if I have a very large dataset (100K) for example?
I think it would still work, because you just trigger one additional change detection round, no matter how big the data is. Another way to trigger another change detection round would be using the ChangeDetectorRef and calling detectChanges.
0

I wonder if virtual scroll makes sense in this case. Concerning the timeout, is it good to put it in knowing that the virtual scroll is designed to handle very large dataset ?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.