How to set up scroll restoration for the Angular Standalone Router?

The Angular Router provides the option to restore scrolling functionality, with documentation on how to implement it when loading data.

Is there a way to configure the standalone router to automatically scroll back to the top of the router outlet?

A demonstration shows that without any specific configuration, if one view is scrolled to the bottom and navigates to another component, the viewport retains that position.

Visit this link for a demo

Answer №1

When you utilize the standalone Angular bootstrapApplication function to supply the router with the provideRouter function, you can set up the router in a way that always scrolls back to the top.

const scrollConfig: InMemoryScrollingOptions = {
  scrollPositionRestoration: 'top',
  anchorScrolling: 'enabled',
};

const inMemoryScrollingFeature: InMemoryScrollingFeature =
  withInMemoryScrolling(scrollConfig);
bootstrapApplication(App, {
  providers: [provideRouter(routes, inMemoryScrollingFeature)],
});

Here's a Demo: https://stackblitz.com/edit/angular-quflkz?file=src%2Fmain.ts

Check out the relevant documentation:

This demo illustrates the consequences of not utilizing scroll restoration.

https://stackblitz.com/edit/angular-adcsej?file=src%2Fmain.ts

Answer №2

If my understanding is correct, you are looking to have the page always scroll up when navigating. What is the reason for this behavior? Typically, when a new page or component is loaded, it starts at the top by default.

One approach is to adjust the scroll position restoration setting in your AppModule or AppRoutingModule based on the documentation you provided.

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { scrollPositionRestoration: 'top' }),
  ],
  exports: [RouterModule],
  providers: [ScrollToTopService],
})

'top' - This setting will reset the scroll position to x = 0, y = 0 upon navigation.

Alternatively, you can implement custom scrolling logic using a service and inject it into the module.

import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

@Injectable()
export class ScrollToTopService {
  constructor(router: Router) {
    router.events.pipe(
      filter(event => event instanceof NavigationEnd)
    ).subscribe(() => {
      window.scrollTo(0, 0);
    });
  }
}

Instead of using scrollPositionRestoration, include the following inside your module:

providers: [ScrollToTopService]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to switch (transpose) the rows and columns of a dynamically generated HTML table from Highchair in Angular 12?

Click here to view the code for creating a highchart table. In the provided example, I have successfully implemented a highchart table using the code below. Highcharts.chart('container', { title: { text: 'Solar Employment Growth by Sec ...

How can I notify a particular user using Node.js?

This is the code I have for my server in the server.js file: var socket = require( 'socket.io' ); var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = sock ...

Issue with rendering Rails View using Javascript

In my show.html file, I have an <a ng-click="writeReview(product)" class="vote-link">Review</a> link. Within my javascript file, I have the following code: $scope.writeReview =(product) -> $http.get("/products/#{product.id}/review/new" ...

Enhancing highcharts gauge with dynamic data from JSON

I've been working hard to get my Gauge looking just right, and now I'm attempting to update it with JSON data from Thingspeak. However, when I check the page, I keep running into a ReferenceError - it says "data is not defined." If you want to t ...

Steps for dynamically loading the correct pane without having to refresh the header, footer, or left navigation

Looking to create a web application using HTML, Bootstrap, and jQuery that includes a header, footer, left navigation, and right pane. The content of the right pane will be loaded from a separate HTML page based on what is clicked in the left navigation. ...

Displaying a dynamic progress bar across all elements in fullscreen mode

I am looking to implement a full-screen indeterminate progress bar that overlays all screen elements. Here is my specific use case: When a user fills out a form, including an email field, the email id is checked against a database via ajax. While waiting ...

Tips for displaying two dynamic variables that are interdependent

For instance: Controller: AllBooks[{ book1:{ hardcover{price:25.99},e-book{price:1.99} } }, book2:{ hardcover{price:60.00},e-book{price:2.99} }]; $scope.bookchoice = function(selectedBook) { $rootScope.choice = selectedBook;} $scope.booktype = functio ...

JavaScript sorting code fails to properly sort numbers

Here is a code snippet that aims to convert a string into an array of numbers and then sort them in descending order. The objective is to find an alternative to the sort() method. However, there seems to be an issue with the current implementation. When t ...

Managing API responses using Redux and Typescript

As a beginner in Typescript, I am struggling to integrate Redux with it. The documentation on using Redux with Typescript is confusing me. I am attempting to fetch data and dispatch it to my reducer for future use, just as I did before adopting Typescript ...

Programmatically Expand and Collapse All nodes in MUI DataGrid using ReactJS

Is there a way to programmatically expand or collapse all rows in MUI ReactJS DataGrid? What have I tried? I attempted to use the defaultGroupingExpansionDepth property as suggested in the MUI documentation: export const EXPAND_ALL = -1; export const COLL ...

Showcase your skills in CSS, HTML, and Javascript

I attempted to search for something similar but came up empty-handed. I have two buttons. When I click one of them, I want to hide a certain division, but it's not working as expected. The divs d2 and d3 are initially hidden when the page opens, whic ...

Issue with Ajax communication to PHP script causing data not to be sent

I am developing a web application that functions as an extensive form which will later be converted into a PDF document. Upon submission of the form, all input data is sent to a PHP file where they are stored as variables to be included in the PDF. Some of ...

Using Angular, implementing conditional statements within a for loop

I am currently working on a project where I have an array being looped inside a tag, using the target="_blank" attribute. The issue is that one of the elements in the array should not have this target="_blank" attribute. What would be the best course of ...

Step-by-step guide on generating a fluid list with Express and HTML

Looking to create a dynamic list by fetching data from a JSON file. I want the list items to redirect me to specific content based on their IDs when clicked. However, my current approach is not working as expected, and the list needs to be truly dynamic. ...

The value I'm receiving for my list of objects is not accurate

Currently, I'm experimenting with implementing TYPEHEAD for user input using the ng-bootstrap library. The goal is to display a list of objects (similar to a select option without a dropdown box): HTML <input type="search" #instance="ngbTy ...

Enhance User Experience with React JS Multi-Select Dropdown Feature

I am dealing with 4 select dropdowns. The values selected should not be available in the remaining dropdown lists. Here is an overview of my state: this.state = { selectedDropdownArray: {}, dropdownArray: ['select', '1', &apos ...

Is there a way to have an HTML scrollbar automatically start at the bottom?

I'm having trouble ensuring that my chatbox's scrollbar automatically starts at the bottom so that new messages are visible without needing to scroll down. The current code I have in JQuery is not achieving this desired behavior. $('#chatbo ...

Having trouble with the mongoose virtual field being undefined while using an arrow function?

Hey, I'm exploring the world of mongoDB! Here's the schema I created: const userSchema = new mongoose.Schema({ firstName:{ type:String, required:true, trim:true, min:3, max:20 }, lastName:{ ...

Error message "Sphere undefined" encountered in ThreeJS Water2 example

I've been experimenting with setting up the basic ThreeJS Water2 example that can be found here: You can access the source code here: https://github.com/mrdoob/three.js/blob/master/examples/webgl_water.html The process appears simple at first glance ...

Is the IE7 Modal Dialog Misaligned?

Update After some investigation, I discovered the root cause of the problem. In my code, I was referencing the height of the overlay, which resulted in different values in IE7 compared to other browsers. To resolve this issue, I adjusted the code to refe ...