Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variable in conditional implementation of ngClass

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.

like image 454
Jayakrishnan Avatar asked Dec 29 '16 11:12

Jayakrishnan


People also ask

How do you write ngClass with condition?

To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.

Can we use NgStyle and ngClass together?

Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.

Can you have multiple ngClass?

Overview. You can use the ngClass directive to conditionally apply one-to-many classes or styles to an element, giving you an effective way to operate with multiple classes or styles at once.

What is the difference between NgStyle and ngClass?

Solution. ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute. Following will be translated to class="deleted" when isDeleted variable is true.


2 Answers

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

like image 59
Günter Zöchbauer Avatar answered Sep 21 '22 18:09

Günter Zöchbauer


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
    }
}
like image 29
borislemke Avatar answered Sep 19 '22 18:09

borislemke