javascriptangulartypescriptscrollfrontend

Angular Scroll Function Not Working for the Last Section of the Page


I'm working on an Angular application where I have a function that scrolls to a specific section on the page. The scrolling works fine for sections 1 through 3, but for some reason, it doesn't scroll to section 4.

Image 1: How it should behave

How it should behave

If I move section 4 higher on the page, the scrolling works as expected. The issue seems to occur only with the last section on the page.

I am aware that pinning section 4 after the navbar could be tricky due to the limited space at the bottom of the page. However, there's still enough space below, so this shouldn't be the cause (as shown in the attached image).

Image 2: Section-4 scrolls to here

Section-4 scrolls to here

Image 3: Section-4 should scroll to here

Section-4 should scroll to here

This problem only occurs locally, and I haven't been able to reproduce it consistently elsewhere. Any insights or suggestions on how to resolve this would be greatly appreciated.

Stackblitz Demo


Solution

  • In this example you are overcomplicating scroll to view.

    I know you have raised multiple questions and would like to stick to this approach. But it's inefficient because when you do routing, it should not render the same component over and over again.

    First add smooth scroll CSS to the global styles.

    section {
      padding-top: var(--nav-height);
    }
    
    html {
      scroll-behavior: smooth;
    }
    

    Then to enable fragment scroll use the below configuration and pass it to withInMemoryScrolling which will enable the scroll to feature.

    const routerOptions: InMemoryScrollingOptions = {
      scrollPositionRestoration: "enabled",
      anchorScrolling: "enabled",
    }
    
    bootstrapApplication(App, {
      providers: [provideAnimations(), provideRouter(routes, withInMemoryScrolling(routerOptions))],
    }).catch((err) => console.error(err));
    

    After this, we just need to update the navigation component to navigate via fragments.

    <nav>
      <ul>
        <li>
          <a [routerLink]="'.'" [fragment]="'section-1'">Section 1</a>
        </li>
    
        <li>
          <a [routerLink]="'.'" [fragment]="'section-2'">Section 2</a>
        </li>
    
        <li>
          <a [routerLink]="'.'" [fragment]="'section-3'">Section 3</a>
        </li>
    
        <li>
          <a [routerLink]="'.'" [fragment]="'section-4'">Section 4</a>
        </li>
      </ul>
    </nav>
    

    You can get rid of the activatedRoute code and the extra routes.


    This gets rid of a lot of complexity, please find below a GitHub repo where the code works fine.

    GitHub repo