August 21, 2017

Scroll to item-of-interest in Angular

Imagine you have a list of elements of some kind (by means of *ngFor). You'd like to make that Component aware of the fragment in the URL so it can scroll to the element identified by it.

For instance, you let the user create a new element in a form in one page and you want that on return, the list scrolls automatically to the item just added. You are using Angular routing facilities.

For more background, you can check the discussion on the issue on the Angular project.

There, some users have provided their approaches. On the basis of some solutions suggested there, I've built my own and it seems to work fine:

[...]

private fragment: string;

constructor(private route: ActivatedRoute { }

ngOnInit() {
this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
}

ngAfterViewChecked(): void {
try {
document.querySelector('#' + this.fragment).scrollIntoView();
} catch (e) { }
}

[...]

I think this adds very little bloat and it handles these situations:

  • No fragment present in the route.
  • Fragment present but invalid (querySelector() throws).
  • Fragment present and valid, but the element is not present.

Actually, the try block is masking these situations rather than handling them. Nevertheless, usually you won't find yourself needing to do anything about them.