我正在将NG-ZORRO用于UI组件,并且已经有了此模板
my-component.component.html
(MyComponent
类)
<nz-tabset [nzSelectedIndex]="selectedIndex">
<nz-tab [nzTitle]="titleTpl">
<ng-template #titleTpl>
<div [routerLink]="['routeOne']"><i nz-icon type="profile"></i>...</div>
</ng-template>
</nz-tab>
<nz-tab [nzTitle]="docsTpl">
<ng-template #docsTpl>
<div [routerLink]="['routeTwo']"><i nz-icon type="file-text"></i>...</div>
</ng-template>
</nz-tab>
</nz-tabset>
<router-outlet></router-outlet>
我需要根据有效路由更改selectedIndex
,无论是routeOne
还是routeTwo
。
映射可能是
{
"routeOne": 0,
"routeTwo": 1
}
很遗憾,我不能使用routerLinkActive
,因为nz-tab
不支持路由。
路线
export const MY_ROUTES: Routes = [
{
path: ':myParam',
component: MyComponent,
children: [
{
path: '',
redirectTo: 'routeOne',
pathMatch: 'full'
},
{
path: 'routeOne',
component: RouteOneComponent
},
{
path: 'routeTwo',
component: RouteTwoComponent
}
]
}
];
所有这些都是因为用户可能想直接访问http://.../123/routeOne
,所以我需要预先选择正确的标签。
我可以通过某种方式完成此操作吗?也许使用ActivatedRoute
或Router
?
答案 0 :(得分:1)
您可以像以前那样利用路由器监听事件:
this.selectedRoute$ = this.router.events.pipe(
startWith(this.router),
filter(
(event) => event instanceof NavigationEnd || event instanceof Router
),
map((event: NavigationEnd | Router) => event.url),
map(path => this.map[path])
);
您可以修改后面的地图以检查路由是否与您的路由匹配,然后使用模板中的异步管道进行订阅,例如:
<nz-tabset [nzSelectedIndex]="selectedRoute$ | async">
....
</nz-tabset>
当您刷新页面或手动导航到该路线时,这也将起作用。
编辑:或订阅ActivatedRoute
以相同的方式检索URL。充分利用可观察的东西,很酷的东西!
祝你好运!
编辑2:如果您只希望针对当前<router-outlet>
范围的路由,则可以像这样使用ActivatedRoute
:
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activated),
map((route) => {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}),
switchMap((route) => route.url)
)
.subscribe((url) => console.log(url));
这应该满足您的需求。