如何在angular4项目中使用多个<router-outlet>
?
当我转到/docs
路径时 - &gt; WelcomeComponent将显示在name = welcome
的出口处
和所有其他路线将显示在默认出口。
app.routing.ts file
import { Routes, RouterModule } from '@angular/router'
import { ModuleWithProviders } from '@angular/core/src/metadata/ng_module'
import { WelcomeComponent } from '../welcome/welcome.component';
export const AppRoutes: Routes = [
{ path: 'docs', component: WelcomeComponent, outlet: 'welcome'},
{ path: '**', redirectTo: '/getSerials/customerId/1027356' }
]
export const AppRouting: ModuleWithProviders = RouterModule.forRoot(AppRoutes, {
useHash: true,
enableTracing: true
})
app.component.html
<div class="row">
<div class="column-sm-12">
<br/><br/><br/>
<router-outlet></router-outlet>
</div>
</div>
</div>
<div>
<div>
<router-outlet name="welcome"></router-outlet>
</div>
</div>
在页面加载时,我在localhost:4200/#/abcd
我有一个(click)= "changeRoute()"
事件的锚标记。
changeRoute() {
this.route.navigate([{ outlets: { welcome: ['welcome']}}])
}
但是当我点击调用changeRounte()函数的anchortag时,当前的url会更改为localhost:4200/#/abcd(welcome:welcome)
,并且永远不会加载welcomeComponent。
答案 0 :(得分:0)
来自评论:
中呈现
localhost:4200/docs
理想情况下,当您转到/docs
时,它应该在WelcomeComponent
<router-outlet name="welcome"></router-outlet>
的HTML
我认为这是对如何使用命名路由器插座的误解。来自spec:
指定商店是辅助路线的目标。
辅助路由看起来像主要路由,您可以配置它们 同样的方式。它们在几个关键方面有所不同:
他们彼此独立。
他们与其他路线合作。
它们显示在指定的插座中。
目前看,您正试图导航到/docs
,但这不是主要路线。据我所知,你是not able to navigate to a secondary route via a url change.
您需要做的是打开主要路线,然后触发辅助路线的打开。
export const AppRoutes: Routes = [
{ path: 'welcome', component: WelcomeComponent, outlet: 'welcome'}, // secondary
{ path: 'docs', component: DocsComponent}, // primary
{ path: '**', redirectTo: '/getSerials/customerId/1027356' }
]
现在将会发生localhost:4200/docs
将在DocsComponent
内呈现<router-outlet></router-outlet>
。
然后,在app.component.ts
内,您可以执行以下操作:
ngOnInit(){
this.router.navigate([{ outlets: { welcome: ['welcome'] }}]);
}
我们在这里找到<router-outlet>
name='welcome'
,然后注入与路由['welcome']
匹配的组件...即上面定义的辅助路由。
所以你渲染的html看起来像......
<div class="row">
<div class="column-sm-12">
<br/><br/><br/>
<router-outlet><!-- DocsComponent content --></router-outlet>
</div>
</div>
<div>
<div>
<router-outlet name="welcome"><!-- WelcomeComponent content --></router-outlet>
</div>
</div>
更新: Working Example