Angular 4 条件 ngClass 导航栏不工作

Angular 4 conditional ngClass navbar not working

我试图让我的导航栏透明,但只在主页上。但令人费解的是,这段代码只适用于 false 条件。 "isHome" 布尔值通过 router.events.subscribe 更新并正常工作。 这是我第一次尝试 Angular 4.

<nav [ngClass]="{'navbar navbar-toggleable-md bg-primary fixed-top navbar-transparent': this.isHome, 'navbar navbar-toggleable-md bg-primary fixed-top': !this.isHome} ">

让我们阅读 ngClass' docs(特别是 object 部分):

Object - keys are CSS classes that get added when the expression given in the value evaluates to a truthy value, otherwise they are removed.

因此,以您的案例为例:

<nav [ngClass]="{
  'navbar navbar-toggleable-md bg-primary fixed-top navbar-transparent': this.isHome,
  'navbar navbar-toggleable-md bg-primary fixed-top': !this.isHome 
}">

意思是:

  1. 当 "home" 计算为真时,类 导航栏、navbar-toggleable-md、bg-primary、固定顶部 navbar-transparent 将被添加。

  2. 一旦 "home" 评估为假,类 导航栏、导航栏可切换的 md、背景主要的、固定顶部将被删除,因为有一个条件添加这些 类 如果 home 评估为 true.

要获得更深入的解释,我建议您查看 issue#5763(comment)


也就是说,解决您的问题很容易。您可以这样做:

<nav class="navbar navbar-toggleable-md bg-primary fixed-top"
     [class.navbar-transparent]="this.isHome">

或者:

<nav class="navbar navbar-toggleable-md bg-primary fixed-top"
     [ngClass]="{ 'navbar-transparent': this.isHome }">

此外,值得一提的是,尽管可以在模板中使用 this.<property>,但不推荐这样做。它可以在未来的版本中被简单地破坏,因为它甚至没有记录。