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:
First way
[ngClass]={'{{className}}': expression}
Second way
[ngClass]= {className: expression}
But neither of them worked.
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.
Combining NgStyle and NgClass Directives with our knowledge of Angular Template Syntax, we can marry conditional styling with Angular's Property & Event Binding.
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.
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.
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
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With