Search code examples
angularangular-cdk-virtual-scroll

Make sort work with CdkVirtualFor and templateCacheSize


I have implemented CdkVirtualForOf on a list in Angular, and set its templateCacheSize to 150 to improve perfomance.

But when I sort my data and scroll, the cached templates screws up the items in the view. In other words: I sort the data, and the list updates correctly. Then I scroll down, but when I scroll up again the entries in the list are incorrect, because of the template caches.

This "issue" is reported on GitHub here.

I have tried disabling the template cache, and this removes the problem, BUT makes the list perform so badly it is almost unusable.

So...

How do I work with this? Is there a way to refresh the cdkVirtualFor template cache? Or is there another way I can make sort work with cdkVirtualFor?

I tried making a minimal repro, but the template cache isn't running although I activated it. I leave it here for reference, or If someone can tell me how to make my repro work.

https://stackblitz.com/edit/angular-ivy-wzfnem?file=src%2Fapp%2Fapp.component.html


Solution

  • I figured out what was wrong. I followed a comment from the Github issue mentioned above, and as suggested, moved my ngOnInit logic to ngOnChanges instead. This fixes the templates not "updating" correctly.