This content originally appeared on DEV Community and was authored by Fateh Mohamed 🐢
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
})
),,
],
};
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();
}
}
Here is a working example
This content originally appeared on DEV Community and was authored by Fateh Mohamed 🐢
Fateh Mohamed 🐢 | Sciencx (2024-08-16T11:31:39+00:00) Angular scroll position restoration between pages (withInMemoryScrolling router settings). Retrieved from https://www.scien.cx/2024/08/16/angular-scroll-position-restoration-between-pages-withinmemoryscrolling-router-settings/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.