Skip to content

Virtual Scroll template caching breaking behavior for Components with ngOnInit #16330

@jeanpaulattard

Description

@jeanpaulattard

It seems that virtual scroll is not rerunning ngOnInit of template components when template views are being cached. This results in having invalid data if the component performs initial functionality on onInit.

Note that the problem below does not happen if template caching is disabled with templateCacheSize: 0.

I've replicated the issue on this stackblitz: https://stackblitz.com/edit/virtual-scroll-pointer-bug

I have the following scenario where I have a component; in the example, PersonComponent; which is repeated for each element of an array within a virtual scroll vieport (see app.component.html). The PersonComponent takes a Person object as an input, and onInit retrieves an Activity object based on some activity ID from an array of Activities that is cached on a service (ActivityService). The retrieved object is then assigned on a variable within the PersonComponent class.

The problem relies when the end user scrolls down and up in the virtual scroll container. When the elements are destroyed and recreated, it seems that the pointers of the activity variable on the PersonComponent is set to point to another incorrect value.

To replicate the problem,

  • Open the stack blits above
  • Take note of the Names and their associated activity.
  • Scroll down on the virtual scroll container (left scroll), and then all the way up
  • Note that the activities associated with the names have changed.

Note that the content of the activity array is not changing, so it's not an issue of some other process changing the content of the object pointed to. Also if you scroll on a normal non virtual scroll container (right scroll), you can note that the data remains the same and does not change.

See also the animated gif below.

virtual scroll bug

I don't know what might be causing the problem, but it seems that it's caused by the virtual scroll functionality.

I've encounted this problem in v7 but it is also present in v8.

Also note that the values that are passed as an @input() are not changed but remain the same.

Expected Behavior

It should be expected that the data that was retrieved onInit is maintained and rendered correctly.

Environment

  • Angular: v8.0.1
  • CDK/Material: v8.0.1 (also present in v7.3.6)
  • Browser: Chrome
  • Operating System: Ubuntu

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3An issue that is relevant to core functions, but does not impede progress. Important, but not urgentarea: cdk/scrolling

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions