DEV Community

Cover image for Angular scroll position restoration between pages (withInMemoryScrolling router settings)
Fateh Mohamed 🐢
Fateh Mohamed 🐢

Posted on

Angular scroll position restoration between pages (withInMemoryScrolling router settings)

It annoys me on some web sites, especially e-commerce and stores, when I scroll over products, visit one product and then loose the scroll position and it just get me to the top of the list and I have to scroll again. 😡

If you are creating a similar application using Angular latest versions, it is really easy to avoid the above issue by enabling a router setting.

Angular introduced ** withInMemoryScrolling ** to customize scrolling behavior. in our case, we have to enable scrollPositionRestoration

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(
      routes,
      withInMemoryScrolling({
        scrollPositionRestoration: 'enabled', // enable position restoration
      })
    ),,
  ],
};
Enter fullscreen mode Exit fullscreen mode

Example

Imagine you have a productList component and a productDetails one.
This is how you have to navigate back to the products list to restore your position.

import { Component, inject } from '@angular/core';
import { RouterModule } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-product-details',
  standalone: true,
  imports: [RouterModule],
  template: `
    <button (click)="back()">Back to products List</button>
  `,
  styleUrl: './item.component.css',
})
export class ProductDetails {
  private location = inject(Location);
  back() {
    this.location.back();
  }
}

Enter fullscreen mode Exit fullscreen mode

Here is a working example

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments. Some comments have been hidden by the post's author - find out more