DEV Community

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

Posted on

5

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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay