2017-02-17 9 views
5

特定のルートにあるときにクラスを追加しようとしています。コードは私のAppComponentにあり、ImはngClassを使っています。特定のルートにあるときにクラスを追加する - 角度2

@Component({ 
    selector: 'my-app', 
    template: `<a [ngClass]="getRoute(router)"> 
     // Some html code.... 
    }) 

、その後、私は同じapp.component.ts

export class AppComponent { 
    getRoute(){ 
    if (this.router.url === '/atendimento'){ 
     return "hide-bar"; 
    } 
    } 
} 

上の機能を持って、私は取得していますエラーは、次のいずれかです。

プロパティ「ルータ」はありませんタイプ 'AppComponent'にはありません

はい、私はRoutes、RouterModule、Router oをインポートしています。 nヘッダー。誰か助けてくれますか?事前

+1

おそらくhttps://angular.io/docs /ts/latest/api/router/index/RouterLinkActive-directive.html? –

+0

このようにしてメソッドにバインドするのは良い考えではありません。変更検出が実行されるたびに呼び出されるため、アプリケーションのパフォーマンスが低下する可能性があります。適切なイベントでフィールドを更新し、代わりにこのフィールドにバインドします。変更検出はフィールドで非常に効率的です。 –

答えて

4

ありがとうございます、あなたのコンストラクタにしてRouterサービスを挿入してくださいルータ

export class AppComponent { 

    constructor(private router:Router) {} 

    getRoute(){ 
    if (this.router.url === '/atendimento'){ 
+1

ありがとう、ガンター、私はあなたのコメントをメモします:) –

2

を注入する必要があります。

import { Router } from "@angular/router"; 
export class AppComponent { 
constructor(private router:Router){} 
    getRoute(){ 
    if (this.router.url === '/atendimento'){ 
     return "hide-bar"; 
    } 
    } 
} 

@Component({ セレクタ: '私のアプリ' テンプレート: ` //一部のHTMLコード.... })

関連する問題