我有一點麻煩這裏瞭解邏輯路由器指令在兩個地方爲同一目的
根組件
import { Component } from "angular2/core";
import { TopNavigationComponent } from "./shared/navigation.component";
import { ArcListComponent } from "./arc/arc-list.component";
import { ArcNewItemComponent } from "./arc/arc-new-item.component";
import { RouteConfig } from "angular2/router";
import { ROUTER_DIRECTIVES } from "angular2/router";
@Component({
selector: "ng2-app",
template: `
<section class="jumbotron full-height">
<top-navigation></top-navigation>
<div class="container">
<router-outlet></router-outlet>
</div>
</section>
`,
directives: [TopNavigationComponent, ArcListComponent,ROUTER_DIRECTIVES]
})
@RouteConfig([
{path: "/", name: "Root", component: ArcListComponent, useAsDefault: true},
{path: "/new", name: "New-item", component: ArcNewItemComponent}
])
export class RootComponent {
}
頂級的導航組件
import { Component } from "angular2/core";
import { ROUTER_DIRECTIVES } from "angular2/router";
@Component({
selector: "top-navigation",
templateUrl: "dev/shared/navigation.template.html",
directives: [ROUTER_DIRECTIVES]
})
export class TopNavigationComponent {
}
navigation.template
<nav class="navbar navbar-default">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" [routerLink]="['Root']">Angular2Arc</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a [routerLink]="['Root']">Home</a></li>
<li><a [routerLink]="['New-item']">Add New Resource</a></li>
<li><a href="#">Github</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
我的問題是,雖然這工作,你能解釋爲什麼我需要把路由器指令放在兩個地方,如果有更好的方法來做到這一點?
將ROUTER_DIRECTIVES放在兩個地方的原因是,您在* RootComponent *中使用* TopNavigationComponent *中的'routerLink'和'routerOutlet'。您可以像'angular2/router''中的import {RouteConfig,RouterOutlet}一樣單獨導入它們。 [檢查這個詳細的例子](https://angular.io/docs/ts/latest/guide/router.html) – Bhavik