在 Angular 2 中使用 <a> 标签链接到其他 html 页面

问题描述 投票:0回答:1

所以我对 Angular 2 非常陌生,我正在使用它来制作个人网站。我有一个主页,上面有个人信息,另一个页面里面有博客内容。这两个页面将具有相同的页眉和页脚,只是其中的正文内容不同。项目文件目录看起来有点像这样,页脚、页眉和博客是组件。

app
├── app.component.html
├── app.module.ts
├── app.component.ts
├── app.component.spec.ts
├── blog
|   ├── blog.component.html
|   └── blog.component.spec.ts
|   └── blog.component.ts  
├── footer
|   ├── footer.component.html
|   └── footer.component.spec.ts
|   └── footer.component.ts
├── header
|   ├── header.component.html
|   └── header.component.spec.ts
|   └── header.component.ts

为了简单起见,我从上面的示例中删除了不相关的文件和 CSS。

现在在我的标题(header.component.html)中 - 我有以下代码,旨在允许用户从主页导航到博客页面并返回

<!-- Header -->
<div class="header container-fluid">
 <div class="col-md-6">
  <img src="logo.jpg" alt="Logo">
 </div>
<div class="col-md-6 offset-6">
 <a href="../../index.html">Home</a>
 <a href="../blog/blog.component.html">Blog</a>
</div>

但是,blog.component.html 页面不会链接。我不明白链接在 Angular 2 中应该如何工作 - 我应该创建另一个 html 页面,其中博客通过其选择器链接还是什么?我觉得这是一个愚蠢的问题,我确信有一个明显的答案——但我似乎无法破解它!我在其他页面上读过有关“路由”的内容,尽管它们似乎是踏板解决方案,当传统 html 和 JS 似乎很容易通过标签链接 html 页面时,这些解决方案看起来非常复杂!

我做错了什么?请有人在这里给我帮助 - 我想要一个简单易用的解决方案。

html angular typescript angular2-routing angular2-template
1个回答
0
投票

首先,您需要为您的应用程序创建一个路由器。您可以在此处找到操作方法。

对于您的应用程序来说,它可能看起来像这样(下面的内容在里面

app.module
):

const appRoutes: Routes = [
  { path: 'blog', component: BlogComponent},
  { path: '',
   redirectTo: '/blog',
   pathMatch: 'full'
  }
];

@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes
    )
    // other imports here
  ],
  ...
})
export class AppModule { }

然后你需要实现

[routerLink]
属性而不是使用 href。
routerLink
就像 Angular 的 href 一样,只不过它保持路由内部并模拟真实的
window.location
更改。

<!-- Header -->
<div class="header container-fluid">
 <div class="col-md-6">
  <img src="logo.jpg" alt="Logo">
 </div>
<div class="col-md-6 offset-6">
 <a routerLink="../../index.html">Home</a>
 <a routerLink="../blog/blog.component.html">Blog</a>
</div>
<router-outlet></router-outlet>
© www.soinside.com 2019 - 2024. All rights reserved.