angular2 target specific router-outlet

只谈情不闲聊 提交于 2019-12-22 11:07: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


回答1:


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




回答2:


Please try write like this, hope it helps.

<a [routerLink]="['/childroute#secureRouterOutlet']">


来源:https://stackoverflow.com/questions/40476814/angular2-target-specific-router-outlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!