Ways to stop Angular from automatically scrolling to the center of the page

I am facing an issue with my angular 11 application. Whenever I navigate to a specific page, there is an automatic scroll down which I don't want. Please refer to the attachment (gif) and homepage.html below to understand the scenario.

https://i.sstatic.net/CtvKj.gif

The navigation point for users is located on homepage.html

<div *ngFor="let section of sections" class="col-md-4 p-2 p-sm-5">
      <div class="bg-red3 box d-flex flex-column justify-content-end p-1 box">
        <a routerLink="sections" class="nav-link"><h4>{{section.name}}</h4></a>
      </div>
    </div>

Attached is the homepage.ts file

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-homepage',
  templateUrl: './homepage.component.html',
  styleUrls: ['./homepage.component.scss']
})
export class HomepageComponent implements OnInit {
  sections = [
    {
      name : 'Classroom Programme',
      background : 'blue',
      image : 'url("https://picsum.photos/200/300"),linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5))',
      'background-position' : 'center center',
      'background-repeat': ' no-repeat',
      'background-size': 'cover',
      'background-blend-mode' : 'overlay',
      key: '1',
    },
    {
      name : 'Distance Learning programme 1(DLP)',
      background : 'blue',
      image : 'url("https://picsum.photos/200/300"),linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5))',
      'background-position' : 'center center',
      'background-repeat': ' no-repeat',
      'background-size': 'cover',
      'background-blend-mode' : 'overlay',
      key:2

    },
    {
      name : 'Drishti Web Store',
      background : 'blue',
      image : 'url("https://picsum.photos/200/300"),linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5))',
      'background-position' : 'center center',
      'background-blend-mode' : 'overlay',
      'background-repeat': ' no-repeat',
      'background-size': 'cover',
      key:3
    },
  ];
  constructor() { }

  ngOnInit() {
  }

}

This is the HTML for the problem page (2nd-page)

 <section id="tags" class="container py-3 py-md-5">
      <div class="row">
        <div class="col-12">
          <a id="{{tag.id}}" class="tag {{selectedId==tag.id ? 'active' : ''}}" (click)="onSelected(tag.id,$event)" *ngFor="let tag of tags">{{tag.name}}</a>
        </div>
      </div>
    </section>
    <div class="container">

      <section class="row">
        <section class="col-12 col-md-4">
          <div class="wrapper p-2 p-sm-4 shadow p-3 mb-5 bg-white rounded">
            <h4>This is title</h4>
            <p>Live from</p>
            <p>2021/01/21</p>
            <button class="btn bg-red3  ml-0 mr-2">get Now</button>
            <button class="btn bg-red3 ml-2 mr-0">Solutions</button>
          </div>
        </section>
        
        //more sections but I cutted it to post the question

Attached is the ts file for the 2nd page

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-sectionspage',
  templateUrl: './sectionspage.component.html',
  styleUrls: ['./sectionspage.component.scss']
})
export class SectionspageComponent implements OnInit {

  constructor() { }

  tags=[
    {
      name: 'Category 1',
      id : 1
    },
    {
      name: 'Cat 1',
      id : 1
    },
    I have added more objects. But now I cut it to post short the question
  ]



  ngOnInit(): void {

  }

  selectedId;
  onSelected(id,event){
    this.selectedId = id;
    console.log(event.target.id);
  }

}

This is the output of ng --serve

Angular CLI: 11.1.1
Node: 12.16.3
OS: win32 x64
Angular: 11.1.0

How can I prevent this scrolling behavior in the specific component of my application?

Answer №1

After some exploration, I uncovered the solution to my query.

To implement smooth scrolling in your App's routing module, make sure to include the following snippet within the RouterModule setup:

RouterModule.forRoot(routes, {scrollPositionRestoration: 'enabled'})

Answer №2

To implement scroll position restoration in app-routing module, include the following line of code: scrollPositionRestoration: 'top'

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

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

What is the best way to populate a dropdown menu by matching keys from an array within an ng-repeat

My JSON structure looks like this: 101 : "List": [ { "Name": "Pink" }, { "Name": "Black" } ] 102 : "List": [ { "Name": "Red" }, { "Name": "Yellow" } ] $sco ...

Leveraging the power of CSS calc() in combination with TailwindCSS styles and JavaScript

Can you explain why applying styles with TailwindCSS v3 to calculations using JS variables does not work? I'm working on a project using VueJS, and I've noticed that styling works fine when using calc as a string like this: ... <div class=&qu ...

Exploring the Power of Vue 3 in Manipulating the DOM

Hello everyone, I am a beginner with Vue and I am interested in learning how to modify the DOM without relying on methods such as document.querySelector or getElementById. Let's take for instance this input: <input id="myInputId" class=& ...

How can I transform an array of text into dropdown options?

Currently, while utilizing Vue and vue-bootstrap, I am facing the task of populating a dropdown menu with an array of text items retrieved from my database. The <b-form-select> component in Bootstrap requires objects of the form {value: 'some va ...

Leveraging both Angular Material UI and Tailwind CSS simultaneously

Recently, I've been incorporating Material UI with Angular. With the deprecation of flexlayout and the rise of Tailwind as a recommended alternative, I'm wondering if it's feasible to utilize both Material UI and Tailwind in tandem. How can ...

Unable to get CSS transition to function properly after adding a class using jQuery

I am trying to create a hover effect that shows an image when the mouse is over a specific div, but for some reason, the transition is not working as expected. I understand that using visibility: hidden cannot be animated. Here is the code snippet: $(d ...

Using jQuery to make a PNG image draggable and allow it to overlap with

Can jQuery's Draggable be used with an overlapping PNG image (not as a background image, but for printing purposes)? I attempted using the CSS style "pointer-events: none," however this solution does not function correctly in Internet Explorer. <d ...

Build a Node.js application with Express to host static files

I am attempting to provide my static files "web.html" and "mobile.html", but I want them to be served only if the user is accessing from a web or mobile device. After some research, I came up with this code: var express = require('express'); va ...

Can you please tell me the CSS pseudo element that corresponds to the AM/PM field in an <input type="time">

The issue with the am/pm display is dependent on the browser that the app is opened in. I am looking for a universal solution to ensure it does not appear in any popular browsers. Below is the HTML code for my input time field: <input type="time" for ...

Creating numerous strings using template literals

I am looking to create multiple strings using a template literal and an array variable. For instance, a template literal allows you to replace an expression with its content in a string: var = "world"; tpl = `Hello ${var}!`; console.log(tpl); // Hello wor ...

Tips for implementing a minimum character length feature in React Material-UI's Autocomplete feature

I am looking to add a 'minimum character length' feature to the autocomplete component in react material-ui. The code snippet below demonstrates what I have so far. constructor(props) { super(props); this.state = { // toggle for ma ...

Are you in need of a JavaScript data validation tool?

Trying to find a library that can validate input in a specific format, such as: { points: array of { x: positive and less than 20, y: positive and less than 15 } } Ideally, it should work on both server and client sides and either return a boolean or th ...

How to update MongoDB documents with referenced objects using Mongoose?

Apologies for any language barriers. I am using node.js + express.js + mongoose.js Here is my schema in mongoose for groups: var groupSchema = new mongoose.Schema({ name: String, users: [{type: mongoose.Schema.ObjectId, ref: 'User'}] ...

What is the most effective way to incorporate JavaScript into a PHP function?

Hey there, I'm currently working on a PHP function that returns HTML/JS content. However, I feel like the approach I'm taking is inefficient and not the best way to do it. Do you have any suggestions for a better method? Here is a simplified ver ...

The tooltip feature for icon buttons within Material UI list items is not functioning properly as anticipated

Just starting out with Material UI and React, I've encountered a strange UI problem that I can't quite figure out. Hopefully someone here can help me identify what I did wrong. My Approach: I have a List in my code where each list item has butto ...

Utilize App.js Constants in Both Controller and View

I am working on a node.js express app that consists of an app.js file, a deviceController.js file, and a cart.pug file. I need to access two constants required for the Stripe API in both the deviceController.js and cart.pug files, and I want to define thei ...

Programmatically control the opening and closing of a React Material UI Snackbar component

Currently, I am facing some challenges while working on programming a Single Page Application (SPA) using React and Material-UI. In my project, I have created a modal login box that gets triggered by a button on the navigation bar. Upon clicking submit, I ...

Encountering an issue with the removal of slides when updating JSON data for angular-flexslider

Issue: Although my JSON object is updating, the slider does not update for all resorts as expected. Sometimes it fails to update when the JSON object changes. The resorts (image collections) that do not update are throwing an error stating "cannot read pr ...

Mastering Angular Apollo Error Resolution Methods

Hey everyone, I'm facing a problem with apollo-angular and apollo-link-error that I just can't seem to figure out. I've experimented with different approaches but have had no luck catching errors on the client-side of my angular web app. Bel ...

Navigate to the following section on an HTML page by clicking a button using jQuery

Within my application using Jquery / Javascript, I am looking to implement a specific functionality. I currently have several div elements like the ones below: <div id="div1"></div> <div id="div2"></div> <div id="div3"></ ...