我是angular2的新手。我试图了解如何在特定模板中使用多个<router-outlets>
。我在这里经历了很多质量保证,但无法解决我的错误。
router.module.ts
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
}
]
},];
component1.html
<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
component2.html
<h3>In two</h3>
component3.html
<h3>In three</h3>
component4.html
<h3>In four</h3>
当我点击 ...转到两个... 打印两个。 但是点击其他两个链接会给我错误无法匹配任何路径
答案 0 :(得分:13)
解决了自己。做了一些小的结构变化也。从 Component1 到 Component2 的路由由单个<router-outlet>
完成。 Component2 到 Comonent3 和 Component4 由多个<router-outlet name= "xxxxx">
完成。结果内容为:
<强> Component1.html 强>
<nav>
<a routerLink="/two" class="dash-item">Go to 2</a>
</nav>
<router-outlet></router-outlet>
<强> Component2.html 强>
<a [routerLink]="['/two', {outlets: {'nameThree': ['three']}}]">In Two...Go to 3 ... </a>
<a [routerLink]="['/two', {outlets: {'nameFour': ['four']}}]"> In Two...Go to 4 ...</a>
<router-outlet name="nameThree"></router-outlet>
<router-outlet name="nameFour"></router-outlet>
'/two'
代表父组件,['three']
和['four']
代表组件2各自子组件的链接
。 Component3.html和Component4.html与问题中的相同。
<强> router.module.ts 强>
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree'
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
}
]
},];
答案 1 :(得分:6)
请将 router.module.ts 修改为:
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
},
{
path: '',
redirectTo: 'two',
pathMatch: 'full'
}
]
},];
并在 component1.html
中<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'