Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple classes with ng-class, where one of the classes is conditional

I got this code:

ng-class="{selectedHeader: key == selectedCol}"

It works but I would like too add the 'key' value as a class too, Ive tried:

ng-class="[{selectedHeader: key == selectedCol}, key]"

But that wont work, does anyone know how to solve this?

like image 490
Jukke Avatar asked Apr 17 '14 07:04

Jukke


People also ask

How do you add ngClass based on 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 you have two 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.

Can we use ngIf and ngClass together?

Now you have learned the basics of Angular directives, including how to use ngIf, ngFor, ngClass, ngStyle, ngModel, and ngSwitch. You can combine them to create more complex user interfaces.

What is the use of ngClass?

The ng-class Directive in AngularJS is used to specify the CSS classes on HTML elements. It is used to dynamically bind classes on an HTML element. The value for the ng-class has either string, an object, or an array. It must contain more than one class name, which is separated by space, in the case of a string.


1 Answers

If you always want key to be added as a class:

ng-class="{selectedHeader: key == selectedCol, key: true]"

or you can just put it into a class attribute with {{}} interpolation.

ng-class="{selectedHeader: key == selectedCol}" class="{{key}}"

Just for completeness, if you only want to include it if it's equal to selectedCol:

ng-class="{selectedHeader: key == selectedCol, key: key == selectedCol}"
like image 75
Michal Charemza Avatar answered Oct 19 '22 23:10

Michal Charemza