Add class when in a specific route - Angular 2

I am trying to add a class when Im on a specific 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 a function on the same app.component.ts

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

The error I am getting is the following:

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

And yes, I import Routes, RouterModule and Router in the header. Can anybody help me?

Thank you in advance

+5
source share
2 answers

You need to enter a router

  export class AppComponent { constructor(private router:Router) {} getRoute(){ if (this.router.url === '/atendimento'){ 
+4
source

Please include the router service in 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", pattern: `// Some html codes ....})

+2
source

Source: https://habr.com/ru/post/1264351/


All Articles