Angular2子组件控制父组件的路由

时间:2016-04-05 06:14:18

标签: javascript typescript angular

我有一个主要的父组件,其中包含一个内置的顶级导航,一个单独的侧边栏导航组件和一个主内容div,其中包含主要组件的<router-outlet>。我试图了解如何在子导航组件中使用链接来更改父主组件中的路由器插座。

```

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{}

```

1 个答案:

答案 0 :(得分: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]="..."它的工作方式相同(第一个示例除外)