Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to conditionally apply a class?

Tags:

css

angularjs

Lets say you have an array that is rendered in a ul with an li for each element and a property on the controller called selectedIndex. What would be the best way to add a class to the li with the index selectedIndex in AngularJS?

I am currently duplicating (by hand) the li code and adding the class to one of the li tags and using ng-show and ng-hide to show only one li per index.

like image 283
respectTheCode Avatar asked Oct 17 '11 10:10

respectTheCode


People also ask

How do you add a class based on a 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.

How do you apply conditional class in react?

The simplest approach is to use a ternary statement inside of a template literal. In this example, banner is always on the div , but active depends on the active prop. If you have a lot of class names that need to be conditional on the same element, it can get a little messy, but it still works.

What is a conditional class?

Conditional Class property allows you to bind an expression which will be evaluated and appended as classes to a widget.


1 Answers

If you don't want to put CSS class names into Controller like I do, here is an old trick that I use since pre-v1 days. We can write an expression that evaluates directly to a class name selected, no custom directives are necessary:

ng:class="{true:'selected', false:''}[$index==selectedIndex]" 

Please note the old syntax with colon.

There is also a new better way of applying classes conditionally, like:

ng-class="{selected: $index==selectedIndex}" 

Angular now supports expressions that return an object. Each property (name) of this object is now considered as a class name and is applied depending on its value.

However these ways are not functionally equal. Here is an example:

ng-class="{admin:'enabled', moderator:'disabled', '':'hidden'}[user.role]" 

We could therefore reuse existing CSS classes by basically mapping a model property to a class name and at the same time keep CSS classes out of Controller code.

like image 179
orcun Avatar answered Sep 27 '22 22:09

orcun