2016-04-05 113 views
2

我有一個主要的父組件,它包含一個內置的頂級導航欄,一個單獨的側欄導航組件和一個主要內容div,其中包含主要組件的<router-outlet>。我試圖讓我的腦海裏有如何讓子導航組件內的鏈接改變父主要組件中的路由器插座。Angular2子組件控制父組件的路由

```

Main Component 
@Component({ 
    selector: 'app', 
    templateUrl: 'mainComponent.html', 
    encapsulation: ViewEncapsulation.None, 
    directives: [ROUTER_DIRECTIVES,ChildSidenav], 
}) 
@RouteConfig([ 
    { path: '/', component: HomeCmp, as: 'Home' }, //for top nav 
    { path: '/about', component: AboutCmp, as: 'About' }, //for top nav 
    { path: '/user', component: UserCmp, as: 'User'}, //for top nav 
    { path: '/data/...', component: SidenavBasicUsage, as: 'Data'}, //link in child component 
    { path: '/dates', component: SelectDatesComponent, as: 'Dates'}, //link in child component 
    { path: '/edit/paths', component: EditPathsComponent, as: 'EditPaths'}, //link in child component 
    { path: '/edit/filters', component: EditFiltersComponent, as: 'EditFilters'}, //link in child component 
]) 
export class AppCmp {} 

Child Component 
@Component({ 
    selector: 'left-control', 
    templateUrl: 'sidebar.component.html', 
    moduleId: module.id, 
    directives: [ROUTER_DIRECTIVES], 
}) 
@RouteConfig([ 
    {path: '/',name: 'Data',component: SelectDataComponent,useAsDefault: true}, 
    {path: '/dates',name: 'Dates',component: SelectDatesComponent}, 
    {path: '/edit/paths',name: 'EditPaths',component: EditPathsComponent}, 
    {path: '/edit/filters',name: 'EditFilters',component: EditFiltersComponent} 
]) 
export class SideNavComponent{} 

```

+0

你想如何瀏覽?在'router.navigateXxx()'或''? –

回答

1

我還沒有嘗試過所有這些方法,但我認爲他們應該工作:

import {Router} from 'angular2/router' 

... 

constructor(private router:Router) {} 

someMethod() { 
    this.router.parent.navigate(['About']); 
    this.router.navigate(['/About']); 
    this.router.navigate(['../About']); 
} 

隨着[routerLink]="..."它的工作原理是相同的(除了第一個例子)

+0

路由器從哪裏來?我試圖從'angular2/router'導入,但它不在那裏。 – blacknight811

+0

我更新了我的答案。我在構造函數':router'中有一個錯字,而不是':Router'。 –

+0

好的我可以使用觸發'''someMethod'''方法的子導航組件上的click事件來完成它。你失去這樣的一件事就是使用''''routerLink'''的'''''''router-link-active''類可以讓你離開盒子。 – blacknight811

相關問題