How to automatically change path in angular when scrolling

36 Views Asked by At

enter image description here

I'm using angular 17, and I want to make a page that contains multiple components but each component can be accessed through a path (when clicking on the navigation menu it automatically scrolls there and changes the path of that specific component) [see the image above]

but when manually scrolling I also want it to be detected by the app and automatically change the path to the correct one according to the component being displayed

1

There are 1 best solutions below

0
Christoph Stickel On

Since you want to point to a specific location inside of a page, I think you should use fragments instead of the path.

In computer hypertext, a URI fragment is a string of characters that refers to a resource that is subordinate to another, primary resource. The primary resource is identified by a Uniform Resource Identifier (URI), and the fragment identifier points to the subordinate resource.

The fragment identifier introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document. The generic syntax is specified in RFC 3986.[1] The hash mark separator in URIs is not part of the fragment identifier.

You can use an Intersection Observer to detect when the component is inside of the viewport and when your fragment should change. Then use NavigationExtras of the routers navigate method to change the fragments.

Code for navigation should look similar to:

this.router.navigate(['.'], {
  fragment: 'about-me'
});