简体   繁体   中英

Angular2 child component controlling routing for parent component

I have a main parent component that contains a built-in top nav, a separate sidebar nav component and a main content div that houses the <router-outlet> for the main component. I'm trying to get my head around how to have the links inside child nav component to change the router-outlet in the parent main component.

```

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

```

I haven't tried all these methods but I think they should work:

import {Router} from 'angular2/router'

...

constructor(private router:Router) {}

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

With [routerLink]="..." it works the same (except the first example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM