所以我是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页面时,它们似乎是非常复杂的解决方案!
我做错了什么?请有人在这里给我帮助-我喜欢一个简单和容易的解决方案。
发布于 2018-02-01 10:40:39
首先,您需要为您的应用程序创建一个路由器。你可以找到how to here。
对于你的应用程序,它可能看起来像这样(下面是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>https://stackoverflow.com/questions/48554486
复制相似问题