0
votes

Here's the plunker: http://embed.plnkr.co/B8feYX7e6oxvI2u4zmYW/

Click on "Child 1" - works. Now click on "Child 2" - does not work. Click "HOME". Click on "Child 2" - works. Now click on "Child 1" - does not work.

Basically navigation from app root to nested router outlet works only once per app life or until you mandatory navigate back to the root first.

Here's some of the code (look at the plunker for the full version):

app.component

@Component({
  selector: 'my-app',
  directives: [ROUTER_DIRECTIVES],
  template: `
    <div>
      <a [routerLink]="['/']">HOME</a>
      <a [routerLink]="['/child', 1]">Child 1</a>
      <a [routerLink]="['/child', 2]">Child 2</a>
    </div>
    <div>
      <router-outlet></router-outlet>
    </div>
  `
})

@Routes([
    { path: 'child/:id', component: ChildContainerComponent }
])    

export class AppComponent { }

child-container.component

@Component({
    directives: [ROUTER_DIRECTIVES],
    template: `
 <div>
    <h3>Child outer container</h3>
    <router-outlet></router-outlet>
</div>
`
})

@Routes([
    { path: '/', component: ChildComponent }
])

export class ChildContainerComponent{
}

child.component

@Component({
    template: `
<div>
    Child: Id={{_id}}
</div>
`
})

export class ChildComponent implements OnInit {
    private _id: number;

    private get routeSegment(): RouteSegment {  // must be better way to get value
        return this._router.routeTree._root.children[0].value;
    }

    constructor(private _router: Router) {
    }

    ngOnInit() {
        this._id = +this.routeSegment.getParam('id');
    }
}
1

1 Answers

2
votes

You need to change your AppComponent Routes to:

@Routes([
    { path: '/child', component: ChildContainerComponent }
])   


And your ChildContainerComponent Routes to:

@Routes([
    { path: ':id', component: ChildComponent }
])


Once you have these routes you can get the Id by implementing OnActivate interface:

import { Router, RouteSegment, RouteTree, OnActivate, Routes } from '@angular/router';

export class ChildComponent implements OnInit, OnActivate {
    private _id: number;

    routerOnActivate(currRoute: RouteSegment, 
                     prevRoute?: RouteSegment, 
                     currTree?: RouteTree, 
                     prevTree?: RouteTree) {

        this._id = +currRoute.getParam('id');
    }
}


Here is a working plunker