简体   繁体   中英

Rendering a child route in the parent in Angular 4

With Angular 2, I could make a child route render "over" its parent by defining an empty path and creating an essentially empty base component. I am trying to accomplish something similar with the new Angular router (version 4.3.1), but have hit a roadblock.

To reproduce my problem, here's a Plunker. The routes are defined as:

[{
    path: '',
    redirectTo: "/master",
    pathMatch: "full"
}, {
    path: 'master',
    component: MasterComponent,
    children: [{
        path: 'detail/:value',
        component: DetailComponent,
        children: [{
            path: 'subdetail',
            component: SubDetailComponent
        }]
    }]
}]

When I navigate to a detail page, the master page is still visible because I have added a <router-outlet></router-outlet> to MasterComponent . What I need is to replace the master view with the detail. I can accomplish this by making detail/:value a sibling of master rather than a child, but this isn't logically correct in my application and breaks my breadcrumbs.

Is there any proper way to handle this kind of pattern, or will I have to pick a workaround, such as showing and hiding the intended route or manually specifying a dedicated "main" outlet for every link ?

The only existing solution that comes close is to define a dummy parent component , but this only works one-level down. If my detail page has another sub-detail page that should also replace master, it gets very messy.

Is there any route-level flag I can set or design pattern to implement to elegantly accomplish this? I am an Angular 2 beginner, but I feel as though something like this should be simple.

First, there is no "new" router in 4.3.1. It's the same router from 2.x.

Second, there were a few changes I needed to make to your plunker to make it work appropriately. The key change was this in the master.component.ts:

<a [routerLink]="['/detail', 5]">

I added a slash. Without the slash it was looking for a route named master/detail/5

The route definition is now flat, so everything will appear "under" your main header.

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'master',
    pathMatch: 'full'
  },
  {
    path: 'master',
    component: MasterComponent
  },
  {
    path: 'detail/:value',
    component: DetailComponent
  }
];

The updated plunker is here: https://plnkr.co/edit/EHehUR6qSi248vQPDntt?p=preview

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