Pieterjan
Pieterjan

Reputation: 3521

Angular - AnchorScolling delay

For a starter, I created a StackBlitz webcontainer here.

I'm using a bootstrap navbar which pushes the content down by incrementing the padding on the .content div. The links inside the navbar point to anchors on the pages.

<h1 class="text-center">Page 2</h1>
<h2 id="part-one">Part 1</h2>
<p>Lorem ipsum ...</p>
<h2 id="part-two">Part 2</h2>
<p>Lorem ipsum ...</p>
<h2 id="part-three">Part 3</h2>
<p>Lorem ipsum ...</p>

When a link is clicked the angular RouterModule navigates to this specific heading tag. But since there is an ongoing animation on the navbar component, angular seems to be confused and doesn't know where to scroll to.

Is there a way to delay the anchor-scrolling, so that it starts after the navbar has collapsed? The ExtraOptions doesn't seem to contain a setting to delay the navigation...

I also considered using a route-guard which returns a promise that resolves true after .4s, but that obviously doesn't work when navigation to an anchor on the same page.

Modify

You can change the behavior by adding/removing the [bsNavbarContent] from the bottom div in the app.component.html

References:

Edit

Angular calls window.scrollTo, but this method doesn't allow you to pass a duration parameter. Sadly this method doesn't have a callback/Promise signature either. So we cannot possibly exactly know when the scrolling has finished.

Here's an open issue which requests a W3 draft update to change scrollTo and scrollIntoView to a Promise, but it's already 5 years old.

The issue contains a post which suggests using an IntersectionObserver, but this won't work when the element is already in the viewport and the anchortag is clicked. (Demo)

Upvotes: 0

Views: 108

Answers (0)

Related Questions