Using variable in conditional implementation of ngClass

9.5k Views Asked by At

I have developed an Angular 2 application in which I am trying to apply a CSS class using ngClass. I have stored the class name in a variable className and tried below code to apply:

  1. First way

    [ngClass]={'{{className}}': expression}
    
  2. Second way

    [ngClass]= {className: expression}
    

But neither of them worked.

4

There are 4 best solutions below

5
On BEST ANSWER

update

[ngClass]="expression ? cssClass : null"

or just

[ngClass]="cssClass"

Plunker example

original (works only in Dart)

[ngClass]= {className: expression}

will work fine when expression returns true

7
On

You should use interpolation like this :

<div  class="{{expression?className:null}}" ></div>

This is a example :

<div  class="{{something===anotherThing?className:null}}" ></div>
0
On

Try below code it works for me.

Assign class in variable:

class1: string = "class1";
class2: string = "class2";

Style:

<style>
.class2 {
    height:50px;
    background-color:red;
    color:white;
    width:100px;            
}
 .class1 {
    height:50px;
    background-color:blue;
    color:white;
    width:100px;
}
</style>

HTML:

<div [ngClass]="1==1?class1:class2">
    Test Class
</div>

Development Tool Code:

enter image description here

Output:

enter image description here

1
On

Instead of setting the condition in your template, you should bind it to a variable or function and return an Object of your class in your controller.

Template

<!-- From a getter -->
[ngClass]="myClass"

<!-- From a function -->
[ngClass]="myClass(someCondition)"

Controller

// As a getter
get myClass(): any {

    return {
        someClass: someTruthyCondition
    }
}

// From a function
myClass(someCondition): any {

    return {
         someClass: someCondition === true
    }
}