angular2 target specific router-outlet

2019-07-02 04:39发布

I have an app that has a base router-outlet that is used as a base for the entire app. then a child router-outlet that is used once a user is logged in to display any components loaded as a result of clicking on a navigation link clicked that is based in the base router-outlet. I want to be able to target the child router-outlet when a navigation link is clicked in the base template.

When I click on a nav item in the base template, it loads the component in the base router-outlet. That makes good sense to me. I would like to know how I can click a nav item in the base template and have the desired component load in the child router outlet.

I can't find any information on targeting a named router-outlet like I could do in RC4 (I think it was RC4) when i used to be able to do something like:

[routerLink]="/childroute#secureRouterOutlet"

Here is a really simple plunker that mimics how things are currently setup: plunkr

2条回答
爷的心禁止访问
2楼-- · 2019-07-02 05:29

Please try write like this, hope it helps.

<a [routerLink]="['/childroute#secureRouterOutlet']">
查看更多
SAY GOODBYE
3楼-- · 2019-07-02 05:35

I would like to know how I can click a nav item in the base template and have the desired component load in the child router outlet

You can achieve that by enabling nested routes, you will need to setup children property on Routes. Here is the doc.

Here is how it can be done, specific to your use case from plunkr.

On src/app.ts specify any components you want to add as children in your Routes configuration. For example, adding Child2Component as nested routes on ChildComponent will be like below

export const ROUTES: Routes = [
    { 
        path: '', 
        component: HomeComponent 
    },
    { 
        path: 'child', 
        component: ChildComponent, 
        children : [
            { path: 'child2', component: Child2Component }  
        ]
    },
    { 
        path: 'home',      
        component: HomeComponent 
    }
];

On the navigation, you will need to add the link to Child2Component as below

<a [routerLink]="['/child', 'child2']">Go to Child - Child2</a>

Now, when you hit that link, ChildComponent will render Child2Component template inside router-outlet in ChildComponent

Here is working plunkr

查看更多
登录 后发表回答