Add a Class when In a certain Route - Angular 2

落花浮王杯 提交于 2021-01-27 05:08:05

问题


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


回答1:


You need to inject the router

  export class AppComponent  { 

    constructor(private router:Router) {}

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



回答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.... })



来源:https://stackoverflow.com/questions/42301299/add-a-class-when-in-a-certain-route-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!