3

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} ">
1
  • Have you tried to see the value of isHome from the template with {{ isHome }} to see if it's changing the value accordingly to the page you're in? Commented Jun 24, 2017 at 12:57

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks!! Because I am just beginning to learn Angular, can you explain to me why my approach does not work?
@KrombopulosMichael you're welcome. I've edited my answer.
Thank you so much, your explanation is really good. I had completely misunderstood the concept so far.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.