2017-12-18 5 views
0

オプションのパラメータと一致するリンク上でアクティブフラグを設定するのは難しいです。ここでAngular2 +必要なオプションのパラメータのrouterLinkActive型ソリューション

は私のルートです:

{ path: 'clients', component: ClientListComponent, canActivate: [AuthenticationGuard] }, 
{ path: 'clients/:id', component: ClientDetailComponent, canActivate: [AuthenticationGuard] }, 

最初は完全なリストである、第二は、選択したidについての詳細です。 (だから私はむしろURLに必要なパラメータを使用しようとしないでください)

ClientListComponentには、「アクティブのみ」(デフォルト)と「すべて」フィルタを表す2つのリンクがあります。

<a [routerLink]="['/clients']" ... 
<a [routerLink]="['/clients', {showAll: 'true'}]" ... 

URLで結果として得られる:私はこれらのためにアクティブなクラスを配線可能性がどのように

/clients 
/clients;showAll=true 

任意の提案ですか?標準routerLinkActiveignores optional parameters

答えて

1

あなたは、ルート変更をサブスクライブし、その後[ngClass]と一緒にルートをマークするためにフラグを使用することができます。

import { Component, OnInit } from '@angular/core'; 
import { Router, Event, NavigationStart } from '@angular/router'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 
    clientFlag = true; 
    showAllFlag = true; 

    constructor(
    private router: Router) { } 

    ngOnInit() { 
    this.router.events.subscribe((e) => { 
     if (e instanceof NavigationStart) { 
     if (e.url === '/clients') { 
      this.clientFlag = true; 
      this.showAllFlag = false; 
     } else { 
      this.clientFlag = false; 
      this.showAllFlag = true; 
     } 
     } 
    }) 
    } 

} 

し、HTMLテンプレート内:

<a [routerLink]="['/clients']" [ngClass]="{'custom-class': clientFlag}" ... 
<a [routerLink]="['/clients', {showAll: 'true'}]" [ngClass]="{'custom-class-2': showAllFlag}" ... 

この種を作るための方法があります。 (経路のチェック、より高度なルート名のチェックなど)、これは一般的な形でどのようにして迅速かつ効率的にカスタムルートチェックを実装できるのでしょうか([routerLinkActive]指令)。

+1

私はあなたの答えを出発点として使い終わりました。そして、 'DefaultUrlSerializer'を使ってイベントの' e.url'をオブジェクトに変換し、私のルートと比較しやすくしました。 –

関連する問題