This question already has answers here:
Angular2 Routing with Hashtag to page anchor

(21个回答)


4年前关闭。




如果问题标题不清楚,我会在网页上添加一些“链接”部分,然后有人可以单击该链接并将其带到同一模板上的某个元素。这并不一定意味着更改URL。

我尝试过的要点:
<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>

这种方法行不通,因为单击链接会将我导航到baseUrl/#sectionA(不存在的路由),而不是页面所属的组件的路由(baseUrl/currentPage#sectionA)。

第一种方法失败了,我尝试了以下方法:
<a href="currentPage#sectionA>Section A</a>
<a href="currentPage#sectionB>Section B</a>
<a href="currentPage#sectionC>Section C</a>

这实际上适用于当前页面,将用户滚动到currentPage上的部分;遇到的问题是当我们的子路线使用相同的组件和模板时。本质上,导航到“baseUrl/currentPage”会将您带到一个空白表格。如果用户要导航到例如“baseUrl/currentPage/1”,我们希望表单中填充数据1(即ID)。

我想要的是用户单击此侧面上下文菜单中的 anchor ,以导航到currentPage和currentPage的参数化路由(currentPage/1,currentPage/31等)所使用的模板上的某个部分。 不重要的是在URL中引用模板上的部分。 我只在乎导航方面对父级及其子级都起作用。绝对最好不要使用第三方 Angular 插件。

非常感谢所有建议和意见。

编辑:
为上下文添加组件路由:
export const CurrentComponentRoutes: Route[] = [
  {
    path: 'currentPage',
    component: CurrentComponent
  },
  {
    path: 'currentPage/:ID',
    component: CurrentComponent
  }
];

上面的路由被导出到主要的app.component路由中:
export const appRoutes: Routes = [
  ...CurrentComponentRoutes,
  ...OtherRoutes
];

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

然后将导出路由导入到主app.module中。另外,我在index.html文件中设置了基本href。

最佳答案

与pe8ter的答案有关,似乎它也可以由[routerLink]激活

请看看这是否对Angular2 Routing with Hashtag to page anchor有帮助

10-06 15:06