2017-02-17 24 views
5

我想添加一個類,當我在某個路線上。代碼在我的AppComponent中,我使用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頭部。有人能幫我嗎?

在此先感謝

+1

也許https://angular.io/docs /ts/latest/api/router/index/RouterLinkActive-directive.html? –

+0

用這種方法綁定到一個方法通常不是一個好主意。每次更改檢測運行時都會調用它,這很容易損害應用程序的性能。而是在適當的事件中更新字段並改爲綁定到此字段。變化檢測對於字段非常有效。 –

回答

4

你需要注入路由器

export class AppComponent { 

    constructor(private router:Router) {} 

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

非常感謝Gunter,我會記下你的評論:) –

2

請注入路由器服務到您的構造函數。

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

@Component({ 選擇: '我的應用程序內', 模板:` //一些HTML代碼.... })