[英]routerLinkActive for dynamic routes by default is active Angular 2
我有两个链接和ngOnInit
动态获取的ngOnInit
。
<li><a [routerLink]="welcomeUrl" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Getting Started</a></li>
<li><a [routerLink]="dashboardUrl" routerLinkActive="active" [routerLinkActiveOptions]="{ exact: true }">Dashboard</a></li>
这是我的组件:
ngOnInit() {
this.dataService.getOptions().subscribe((options: Options) => {
if (options.mode.toLowerCase() === "live") {
this.dashboardUrl = '/';
this.welcomeUrl = 'welcome';
} else {
this.dataService.getName().subscribe((name: string) => {
this.dashboardUrl = name;
this.welcomeUrl = name + '/welcome';
});
}
});
}
和路线:
const routes: Routes = [
{ path: '', component: DashboardComponent },
{ path: 'welcome', loadChildren: 'app/welcome/welcome.module#WelcomeModule' },
{ path: ':name', component: DashboardComponent },
{ path: ':name/welcome', loadChildren: 'app/welcome/welcome.module#WelcomeModule' },
];
但是,当我启动应用程序时,这些链接是活动的。 单击更改URL的链接后,它们开始正常工作。
默认情况下,这些链接(URL)为空并且始终处于活动状态吗? 我该如何解决?
首先,编写[routerLink]
(带有[ ]
)使指令期望一个数组,因此您的代码应为:
<a [routerLink]="welcomeUrl" routerLinkActive="active">...</a>
但是我认为问题是由于代码的异步性质造成的: routerLinkActive
在设置welcomeUrl
之前执行,并且无法完成其工作。
解决方案1:用*ngIf
包裹链接(快速且肮脏)
用测试将您的链接包裹起来,仅在设置了变量后才显示它们:
<ul *ngIf="welcomeUrl && dashboardUrl">
<li><a [routerLink]="welcomeUrl" routerLinkActive="active">Getting Started</a></li>
<li><a [routerLink]="dashboardUrl" routerLinkActive="active">Dashboard</a></li>
</ul>
解决方案2:移动异步调用(功能更强大,但工作更多)
另一个选择是将您的异步调用( this.dataService.getOptions()
移至在激活包含routerLinks的组件之前执行的点。
在不知道组件的组织方式的情况下很难做到更加具体,但是:
resolve
参数,并在resolve内部调用this.dataService.getOptions()
。 解析将获取“模式”,然后通过ActivatedRoute.data["mode"]
将其传递给组件。 请参阅有关解析的文档: https : //angular.io/docs/ts/latest/guide/router.html#resolve-guard this.dataService.getOptions()
并通过@Input
将“模式”传递给子@Input
。 在这两种情况下,想法都是相同的: 在激活包含routerLinks的组件之前先确定“模式”,以便可以在执行routerLinkActive
之前设置welcomeUrl
和dashboardUrl
变量。
要测试异步调用是否确实是您造成问题的原因,请尝试使用*ngIf
解决方案,并查看其是否有效。
尝试这个:
<li>
<a [routerLink]="dashboardUrl" routerLinkActive="active"
[routerLinkActiveOptions]="{exact: true,__change_detection_hack__:dashboardUrl}">
Dashboard
</a>
</li>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.