Skip to content

bug(cdk/scrolling): scrollToIndex in Angular lifecycle hooks #26702

Open
@hughknaus

Description

@hughknaus

Is this a regression?

  • Yes, this behavior used to work in the previous version

The previous version in which this bug was not present was

No response

Description

Trying to automatically scroll to a specific item in the CdkVirtualScrollViewport when loading an Angular component using the scrollToIndex(index: number, behavior = 'auto') method. I have tried placing the scrollToIndex method in various lifecycle hooks, ngOnInit, ngAfterContentInit, ngAfterViewInit, and ngAfterViewInit.

scrollToIndex inside of ngOnInit, ngAfterContentInit, or ngAfterViewInit do nothing and no errors thrown.

ngAfterViewInit of course fires multiple times and trying to limit the scrollToIndex to only firing the first time does not work and no errors thrown.

How would one scroll to the index of an item after the page loads without using setTimeout? Perhaps I am just using it wrong?

Reproduction

Steps to reproduce:

  1. Providing an example with the different lifecycle hooks: https://stackblitz.com/edit/angular-cdk-programatically-scroll-4kwju2?file=app%2Fcdk-virtual-scroll-fixed-buffer-example.ts

Expected Behavior

Expect to be able to scroll to an item in Angular lifecycle hooks (other than ngAfterViewChecked which fires multiple times).

Actual Behavior

scrollToIndex does nothing and no errors when used in lifecycle hooks.

Environment

  • Angular: latest
  • CDK/Material: latest
  • Browser(s): Chrome
  • Operating System (e.g. Windows, macOS, Ubuntu): Windows and/or macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    P4A relatively minor issue that is not relevant to core functionsarea: cdk/scrolling

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions