7

I'm trying to add a class when Im on a certain route. The code is in my AppComponent, Im using ngClass.

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

and then I have the function on the same app.component.ts

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

The error I'm getting is the following one:

Property 'router' does not exist on type 'AppComponent'

And yes, I am importing Routes, RouterModule and Router on the header. Can someone help me?

Thanks in advance

2
  • 1
    Perhaps angular.io/docs/ts/latest/api/router/index/… ? Commented Feb 17, 2017 at 15:18
  • Binding to a method this way is usually not a good idea. It will be called every time change detection runs and this is prone to harm the performance of your application. Rather update a field at appropriate events and bind to this field instead. Change detection is quite efficient with fields. Commented Feb 17, 2017 at 15:20

2 Answers 2

5

You need to inject the router

  export class AppComponent  { 

    constructor(private router:Router) {}

    getRoute(){
     if (this.router.url === '/atendimento'){
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Gunter, I'll take note of your comments :)
2

Please inject Router service in to your constructor.

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

@Component({ selector: 'my-app', template: ` // Some html code.... })

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.