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

左心房为你撑大大i 提交于 2019-12-13 12:57:53

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/40404257/angular-2-anchor-links-to-element-on-current-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!