Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Anchor Links to Element on Current Page [duplicate]

In case the question title is unclear, I have a webpage with some section "links," whereupon someone could click the link and be brought to an element on the same template. This does not necessarily mean changing the URL.

The gist of what I've tried:

<a href="#sectionA>Section A</a>
<a href="#sectionB>Section B</a>
<a href="#sectionC>Section C</a>
<br/>
<div id="sectionA">
   <p> Content for A </p>
</div>
<div id="sectionB">
   <p> Content for B </p>
</div>
<div id="sectionC">
   <p> Content for C </p>
</div>

This approach did not work because clicking the link would navigate me to baseUrl/#sectionA (nonexistent route), rather than the route of the component the page was a part of (baseUrl/currentPage#sectionA).

The first approach failing, I tried the below:

<a href="currentPage#sectionA>Section A</a>
<a href="currentPage#sectionB>Section B</a>
<a href="currentPage#sectionC>Section C</a>

This actually works for the current page, scrolling the user to the section on the currentPage; the issue encountered is when we have a child route using the same component and template. Essentially, navigating to 'baseUrl/currentPage' takes you to an empty form. Were a user to navigate to, for example, 'baseUrl/currentPage/1', we would expect the form to be filled out with data for 1, which is an ID.

What I would like is for a user to click an anchor in this side context menu to navigate to a section on the template utilized by both currentPage and the parameterized routes of currentPage (currentPage/1, currentPage/31, etc.). What is not important is that the section on the template be referenced in the URL. I only care that the navigation aspect be functional for the parent and its children. It is definitely preferable to not have to use third-party angular plugins.

All suggestions and input are much appreciated.

Edit: Adding component routes for context:

export const CurrentComponentRoutes: Route[] = [
  {
    path: 'currentPage',
    component: CurrentComponent
  },
  {
    path: 'currentPage/:ID',
    component: CurrentComponent
  }
];

The above routes are exported to main app.component routing:

export const appRoutes: Routes = [
  ...CurrentComponentRoutes,
  ...OtherRoutes
];

export const routing: ModuleWithProviders = RouterModule.forRoot(approot);

Export routing is then imported into main app.module. Additionally, I have set base href in index.html file.

like image 671
j.k Avatar asked Nov 03 '16 14:11

j.k


1 Answers

related to pe8ter's answer, seems it can be activated by [routerLink] as well

please see if this helps Angular2 Routing with Hashtag to page anchor

like image 185
Jonathan Niu Avatar answered Nov 09 '22 22:11

Jonathan Niu