[英]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.