Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a Class when In a certain Route - Angular 2

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

like image 487
Renê Silva Lima Avatar asked Feb 17 '17 15:02

Renê Silva Lima


People also ask

What would you use in angular 2 to define routes?

We use the router-outlet directive, an Angular 2 Routing directive that displays the active route (like ng-view ).

What is the correct way to add a basic route in Angular?

First, add links to the two components. Assign the anchor tag that you want to add the route to the routerLink attribute. Set the value of the attribute to the component to show when a user clicks on each link. Next, update your component template to include <router-outlet> .

What does ActivatedRoute do in Angular?

ActivatedRoutelink. Provides access to information about a route associated with a component that is loaded in an outlet.


1 Answers

You need to inject the router

  export class AppComponent  { 

    constructor(private router:Router) {}

    getRoute(){
     if (this.router.url === '/atendimento'){
like image 99
Günter Zöchbauer Avatar answered Nov 11 '22 09:11

Günter Zöchbauer