Search code examples
angularng-class

Angular 4 conditional ngClass navbar not working


I´m trying to make my navbar transparent but only on the homepage. But this code is puzzlingly only working on the false condition. "isHome" Boolean is updated via router.events.subscribe and working properly. This is my first attempt on 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} ">

Solution

  • Let's read the ngClass' docs (especifically object part):

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

    So, taking your case as example:

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

    It means that:

    1. When "home" evaluates to true, the classes navbar, navbar-toggleable-md, bg-primary, fixed-top and navbar-transparent will be added.

    2. Once "home" evaluates to false, the classes navbar, navbar-toggleable-md, bg-primary, fixed-top will be removed, because there's a condition to add these classes if home evaluates to true.

    For a deep explanation I'd recommend you to check issue#5763(comment).


    That said, to solve your problem is pretty easy. You can do either this:

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

    Or:

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

    Also, it's worth to mention that even though it's possible to use this.<property> in template it isn't recommended. It can be simply broken in future releases since it isn't even documented.