Issues have been reported with Angular 10's router and anchorScrolling feature when used within a div that is positioned absolutely and has overflow set

I feel like I may be doing something incorrectly, but I can't quite pinpoint the issue. Any help or pointers would be greatly appreciated.

My current setup involves Angular 10 and I have activated anchorScrolling in the app-routing.module file.

const routes: Routes = [
  { path: 'docs', component: DocsComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    useHash: true,
    anchorScrolling: 'enabled'
  })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Everything works perfectly fine as long as the container for the jump-sections (sections with #id where scrolling is desired) does not have the overflow:auto property set. However, if I do set the overflow:auto property, then the scrolling stops working through anchorScrolling. Manual scrolling or typing the URL with the fragment still works though.

To demonstrate this issue, I have created a StackBlitz project.

Check out the StackBlitz project here

If you add

overflow:auto

to the

.sections 

class in the hello.component.css file, you will notice that the section links at the top no longer trigger scrolling even though the URL updates correctly with the route#fragment.

Is this behavior expected?

Answer №1

I spent several minutes trying to understand the issue at hand. Unfortunately, I couldn't quite grasp it, but I did manage to achieve what I believe was your original goal.

In my modifications (specifically in hello.component.css), I made the following changes:

.sections{
  position:relative;
  top:5rem;
  border:2px solid rebeccapurple;
  overflow:auto; 
}

I eliminated the height specification that was previously set for the 'absolute' value in the position property. Furthermore, I switched the position property's value to 'relative'.

Initially, setting the position as 'absolute' seemed to work fine. However, once width and height values were applied, the functionality would cease to operate.

Answer №2

Based on information provided in this response, I have developed a solution that eliminates the need for fragments while still functioning effectively.

To implement this solution, you will need to modify your a elements as shown below:

<a (click)="toSection('1')">Section 1</a>
. Ensure to update the section number accordingly for each respective section.

In addition, include the following method in your component:

toSection(section: string){
  const elem = document.getElementById("section-"+section);
  const topPos = elem.offsetTop
  document.getElementById('sections').scrollTo({top:topPos-10, behavior:'smooth'})
}

The adjustment of topPos-10 enhances the visual appeal by preventing the div from being directly aligned with the section title.

Note: This approach offers the benefit of not appending #section to your URL.

For a live example, refer to the stackblitz link here.

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

Error: "$$" not defined in this context

I am currently working on generating a dynamic pie chart programmatically with the intention of transforming it into a reusable React Component. The main idea is to have an interactive pie chart where each slice expands into a full pie when clicked. I came ...

Creating CSS rounded corners with pseudo-elements

Take a look at this fiddle: https://jsfiddle.net/xnr7tqm1/ This is the html code I'm working with: <div class="media-container"> <iframe width="365" height="200" src="https://www.youtube.com/embed/JqjIb6FhU_k" frameborder="0" al ...

Creating a Dynamic Navigation Bar with HTML and CSS

I've been exploring the code on w3schools.com, and while there are some great examples, I'm struggling to understand it all. Unfortunately, there aren't any instructions on customizing the code for a third level of menus. Can someone simplif ...

Link the same CSS file with multiple HTML pages

Currently, I am in the process of creating an external CSS file specifically for my homepage. The only issue I am encountering is that while I know how to resolve this problem for one HTML page, I am uncertain about how to address it for other pages. For ...

Error: JSON parsing error - Unexpected token at the start of the JSON data when using JSON.parse() function

Backend code router.route('http://localhost:5007/api/media') .post(mediaCtrl.saveMedia) async saveMedia(req, res) { let file = req.files.file let ext = req.body.extension let path = req.body.path if(_.isNull(file) || _.isEmp ...

Is there a way to verify if this route leads to a valid page?

I am currently using Angular 5 along with localize-router. Unfortunately, localize-router does not support paths without a language prefix (only the main page), so I decided to create a component to handle this issue. In my router configuration, I have set ...

I can't seem to get the button to function properly, and it's really

I am having an issue with my "Let's Get Fit" button. When I hover over it or click it, the cursor doesn't change and it doesn't lead to index.html. I'm not sure why it's not working. .btn { display: inline-block; text-transf ...

Enhance the aesthetics of placeholder text in Semantic UI React using CSS styling

Currently, I am utilizing Semantic UI dropdowns within my React application to generate drop-down menus similar to the ones showcased in their documentation found here: The initial text displayed is "Select Friend", and it appears with a semi-transparent ...

Combine an array of objects that are dynamically created into a single object

Having trouble transforming the JSON below into the desired JSON format using JavaScript. Current JSON: { "furniture": { "matter": [ { "matter1": "Matter 1 value" }, { "matter2": "Matter 2 value" }, { ...

Having trouble rendering components due to conflicts between React Router and Semantic UI React

Below is the code in my App.js: import { useRecoilValue } from 'recoil'; import { authState } from './atoms/authAtom'; import { ToastContainer } from 'react-toastify'; import { ProtectedRoute } from './layout/ProtectedRou ...

Dealing with Angular CORS Problems While Sending Successive Requests

I am currently working with Angular 6 and my backend consists of a node API. Occasionally, I encounter a CORS issue while making HTTP GET requests every 5 seconds. const url = 'https://<removed>.com/api/v1/transactions/' + transactionI ...

Dynamically align text in the center of an image, vertically

I'm trying to create a hover effect where an image and text are displayed in the center of the image when someone hovers over it. Here is how the HTML looks: <article> <div class="entry-content"> <a href="http://www.linktopost.com"> ...

Enhancing Angular2 Forms with ngControl

I'm attempting to utilize ngControl in order to add error classes based on the user's input. However, I am facing challenges trying to make it work effectively. I can see that the appropriate classes are being set (line ng-invalid), but when I a ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

What are the best techniques for positioning text next to images in HTML and CSS?

I have attempted to position the text in close proximity to the images as shown in the picture below (to allow for spacing in the middle). As depicted in the image, the "AVENUE FOR GROWTH" and "NETWORKING OPPORTUNITIES" texts are near Man's hand and w ...

CSS Only flyout navigation - reveal/hide with a tap or click

I want to make adjustments to a CSS-only menu that has a horizontal flyout effect triggered by hovering. I am looking to achieve the same effect on touch or tap - meaning, one tap to open the menu and another tap to close it. Is it possible to accomplish ...

Are we utilizing this JavaScript function properly for recycling it?

Two functions have been implemented successfully. One function adds the autoplay attribute to a video DOM element if the user is at a specific section on the page. The other function smoothly slides in elements with a transition effect. The only limitatio ...

Experiencing difficulties with running the prefixer script in npm

I'm facing issues while trying to run prefix CSS despite having installed the necessary npm packages like prefixer and postcss-cli in my development environment. When attempting to run the prefixer for my CSS file, I encountered some errors. Here&apos ...

Unable to change background-image as intended

Here is an example of my HTML code with an initial background image: <div id="ffff" style="width: 200px; height: 200px; background-image: url('/uploads/backroundDefault.jpg')">sddsadsdsa<br>dffdsdfs</div> Everything seems to b ...

Unable to hear sound on Mozilla Firefox

I am facing an issue with playing an audio file using the audio tag inside the body element. The audio plays perfectly in Chrome once the body has finished loading, but it fails to play in Mozilla Firefox. I even attempted to download the audio file and pl ...