【问题标题】:Add a Class when In a certain Route - Angular 2在某个路线中添加一个类 - Angular 2
【发布时间】:2017-07-07 04:17:13
【问题描述】:

当我在某条路线上时,我正在尝试添加一个类。代码在我的 AppComponent 中,我使用的是 ngClass。

    @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。有人能帮我吗?

提前致谢

【问题讨论】:

  • 以这种方式绑定到一个方法通常不是一个好主意。每次更改检测运行时都会调用它,这很容易损害您的应用程序的性能。而是在适当的事件中更新字段并绑定到该字段。更改检测对于字段非常有效。

标签: angular routing ng-class


【解决方案1】:

请将路由器服务注入您的构造函数。

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

@组件({ 选择器:'我的应用', 模板:` // 一些 html 代码.... })

【讨论】:

    【解决方案2】:

    你需要注入路由器

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

    【讨论】:

    • 非常感谢 Gunter,我会注意你的 cmets :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2017-12-14
    相关资源
    最近更新 更多