1

Started to learn Angular 5 and am stuck with ngClass directive. I am trying to apply multiple classes based on a condition, but somehow only 1/2 classes are being applied.

mainnav.component.html

<nav class="navbar navbar-expand-lg fixed-top"
    [ngClass]="{
    'navbar-dark bg-dark' : themeColor === 'dark',
    'navbar-dark bg-primary' : themeColor === 'blue',
    'navbar-light bg-light' : themeColor === 'light'
    }">
...
...
<li class="nav-item">
    <form class="form-inline my-2 my-lg-0">
    <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" (keyup)="onButtonClicked($event)">
    <button class="btn btn-outline-success my-2 my-sm-0" [disabled]="!allowSearch" type="submit">Search</button>
    </form>
</li>
<li class="nav-item dropdown" (mouseover)="openDropDown($event)">
    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Change Theme
    </a>
    <div class="dropdown-menu" aria-labelledby="navbarDropdown">
    <a class="dropdown-item" href="#" (click)="enableDarkTheme()">Dark</a>
    <a class="dropdown-item" href="#" (click)="enableLightTheme()">Light</a>
    <a class="dropdown-item" href="#" (click)="enableBlueTheme()">Blue</a>
    </div>
</li>

mainnav.component.ts

themeColor: string = 'dark';
enableDarkTheme() {
    this.themeColor = 'dark';
  }

  enableLightTheme() {
    this.themeColor = 'light';
  }

  enableBlueTheme() {
    this.themeColor = 'blue';
  }

The conditions seems to be working fine, but I am not sure why one class is not added as seen in screenshot below,

enter image description here

Does anyone know if my usage of ngClass is wrong?

1 Answer 1

2

There is a previous bug report in the Angular GitHub repo on this very topic.

The reason is because [ngClass] will add classes for the ones that resolve to true and remove classes for those that resolve to false. You are using the same class in multiple cases which creates the problem.

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

1 Comment

Interesting! I also missed the point of ngClass that it removes classes if the condition is false. Thanks for the link :) For sake of completeness, this is my new code - [ngClass]="{ 'navbar-dark' : themeColor === 'dark' || themeColor === 'blue', 'bg-dark' : themeColor === 'dark', 'bg-primary' : themeColor === 'blue', 'navbar-light bg-light' : themeColor === 'light' }

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.