Angular - enabling scroll position restoration for a singular route

Is there a way to turn off scroll restoration on a specific page? Let's say I have the following routes in my app-routing.module.ts file...

const appRoutes: Routes = [{ path: 'home', component: myComponent}, { path: 'about', component: myComponent}, ]

and my imports are set up like this...

@NgModule({imports: [RouterModule.forRoot(appRoutes, {
    scrollPositionRestoration: 'enabled'
})]

So how can I disable scroll restoration for the 'about' route?

Answer №1

Avoid using:

scrollPositionRestoration: 'enabled'

Go back to the original setting:

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

Now, implement this in your home.component.ts file only:

scrollTop() {
    window.scroll(0, 0);
  }

Finally, add (click)="scrollTop()" wherever you want it to be executed.

Answer №2

Managing the scrollPositionRestoration value for different routes can be challenging as it is typically set at the root module level. Therefore, in your situation, it may be necessary to remove this setting from the root module (where it defaults to 'disabled') and instead control the scroll position using the Router and ViewportScroller. Within the app.component, you can track navigation events like so:

this.router.events.subscribe((e) => {
  if (e instanceof NavigationEnd) {
    // Add any logic here for scrolling to the top or elsewhere
    this.viewport.scrollToPosition([0, 0]);
  }
});

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

typescriptCreating a custom useFetch hook with TypeScript and Axios

I have a query regarding the utilization of the useFetch hook with TypeScript and Axios. I came across an example of the useFetch hook in JavaScript, but I need help adapting it for TypeScript. The JavaScript implementation only handles response and error ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

Google+ login is functional on browsers but not on smartphones when using Ionic 2

Successfully logged in using Google+ on my app. It works fine when checked on Chrome/Explorer, but on my smartphone or Android emulator, after pressing "login with Google+", it shows a successful login message but stays on the same login page without progr ...

CSS: Achieving Full Container Width Text with Respect to Another Container's Height

Hello, I am facing a very specific issue that I can't seem to resolve: I have two containers (ion-card) and I want them to always be the same height. I was able to achieve this by following the solution provided here: https://i.sstatic.net/he8O7.png ...

Stopping the infinite refresh issue in your React webpack application

Every time I modify the TS file, Webpack keeps refreshing the page without stopping. The console message reads: "@ebpack 5.66.0 compiled successfully" I've searched online and experimented with various plugins, but none of them seem to solve the issu ...

Requires the refreshing of an Angular component without altering any @Input properties

Currently delving into the world of Angular (along with Typescript). I've put together a small application consisting of two components. This app is designed to help track work hours (yes, I am aware there are commercial products available for this pu ...

Using TypeScript with Angular UI Router for managing nested named views in the application

Hey there! I am new to typescript and have a bit of experience with Angular. Lately, I've been struggling to make a common angular-ui-router setup work with typescript. I have a nested named views structure that just doesn't seem to load correctl ...

The issue is that TypeScript is indicating that the type 'string | string[]' cannot be assigned to the type 'string'

https://i.sstatic.net/ZaJvb.pngI recently upgraded to Angular 16 and encountered an issue with an @Input() property of type string | string[]. Prior to the upgrade, everything was functioning correctly, but now I am experiencing errors. I am uncertain abou ...

What potential drawbacks come with utilizing the OOP approach in both JavaScript and React?

While working on an internal project, I found myself creating a base system and implementing a custom form structure using TypeScript with an OOP approach. class Form extends React.Component {} abstract class FormElement extends React.Component<{valid ...

What is the best way to implement NgClass on a single iteration within NgFor while utilizing parent/child components?

My goal is to toggle the visibility of tiered buttons when a parent button is clicked. I am using ngFor to generate three buttons on tier 1, but I'm struggling to select only the desired tier when clicked instead of affecting all of them. I've m ...

Why is it advantageous to use Observable as the type for Angular 5 component variables?

Being a beginner in Angular 6, I have been exploring the process of http mentioned in this link: https://angular.io/tutorial/toh-pt6#create-herosearchcomponent One thing that caught my attention was that the heroes array type is set to Observable in the ...

Tips on transferring key values when inputText changes in ReactJs using TypeScript

I have implemented a switch case for comparing object keys with strings in the following code snippet: import { TextField, Button } from "@material-ui/core"; import React, { Component, ReactNode } from "react"; import classes from "./Contact.module.scss" ...

Retrieve the value within the finalize pipe from a test execution

I have a component with the following code: isLoading: boolean; users: User[]; test: number = 1; ngOnInit() { this.isLoading = true; this.userService.getUsers() .pipe( finalize(() => { // Disable loading when complete ...

Validation scheme for the <speak> element

When using validators in an angular formarray for input fields, I encountered a challenge with the regex to check the <speak> tag. https://i.sstatic.net/ogFA3.png The content provided was considered valid. https://i.sstatic.net/ar5FJ.png An error ...

Investigating SCSS Issues: The Problem with Absolute Imports

I am working on a project with the following structure: - my/project - assets - images - image-name.svg - source - components - MyComponent - MyComponent.module.scss - ... - ... ...

Tips for updating routerlink in navigation bar in Angular 4

I'm encountering an issue with routing to the wrong routelink. How can I prevent this from happening? My apologies for my lack of experience. The error message displayed in the Chrome console is: ERROR Error: Uncaught (in promise): Error: Cannot mat ...

Accessing the access token in your Angular application right after the login process with Auth0

I've been working on integrating auth0-spa-js in my Angular application, and I'm encountering an issue extracting the access token after a successful user authentication. Despite reading multiple articles on the topic, I'm still unclear on h ...

What is the meaning of boolean true in a Firestore query using TypeScript?

Currently, I am facing an issue with querying Firestore in Angular 8 using AngularFire. While querying a string like module_version works perfectly fine as shown in the code snippet below, the problem arises when attempting to query a boolean field in Fire ...

The mat-datepicker is being displayed beneath the content

My Angular material design datepicker is displaying underneath the content. Within my module, I have a component that is rendered inside app-root. This component includes a mat-stepper with a mat-datepicker inside one of the steps. This is how the genera ...

My goal is to monitor every action (button) that users take while using the PDF viewer

Each browser displays the view differently, and I am interested in monitoring specific user actions such as button presses on a PDF viewer. I am currently setting up an iframe and configuring its attributes. Is there a way to achieve this? ...