So I'm very new to Angular 2 and I'm using it to make a personal website. I have a main page with bio information on it and another page where I'll have blog content inside it. Both these pages will have the same header and footer with simply different body content inside them. The project file directory looks a bit like this, with footer, header and blog being components.
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
For simplicity, I've taken out irrelevant files and CSS from the above example.
Now in my header (header.component.html) - I have the following code which intends to allow users to navigate from the home page to blog page and back
<!-- 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>
However, the blog.component.html page won't link. I don't understand how links are supposed to work in Angular 2- should I create another html page where the blog is linked through it's selector or what? I feel like this is a stupid question and I'm sure there's an obvious answer- I just can't seem to crack it though! I've read stuff about 'routing' on other pages, although they seem to be pedaling solutions that seem so complicated when traditional html and JS seem to link up html pages through a tags so easily!
What am I doing wrong? Please someone give me help here- I would love a simple and easy solution.
答案 0 :(得分:0)
首先,您需要为您的应用程序创建一个路由器。您可以找到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]
属性而不是使用hrefs。 routerLink
类似于角色的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>