Adding multiple class using ng-class
Adding multiple class using ng-class
270
17-Jun-2024
Updated on 18-Jun-2024
Ashutosh Kumar Verma
18-Jun-2024Add multiple classes using
ng-class
In AngularJS, you can use the
ng-class
directive to dynamically apply multiple classes to an element based on expressions in your controller or directly in your template.Here’s how you can do this.
Use object syntax
You can use object syntax with ng-class where each key is a class name and its value is a boolean expression indicating whether the class should be used.
in the above syntax
class1, class2, and class3 are optional class names.
condition1, condition2, and condition3 are boolean expressions that specify the scope of your controller indicating whether each class should be used (true) or not (false).
Example
HTML
Controller
In this case
<div>
have red and italic classes, becauseisError
andisItalic
are true,isImportant
is false.Array Syntax
You can also use an array syntax with
ng-class
where each element in the array is a class name added with no entry.Example-
In the example above
'
alert
' and 'alert-
' + type are added with nothing as class.{ 'alert-dismissible': dismissible }
There is an object to add the alert-dismissible class ifdismissible
evaluates totrue
.Combining Methods
You can also combine both methods for more flexibility.
In the example above
class1
is added unconditionally.class2
is added if condition2 evaluates to true.class3
is added unconditionally.Example-
here is a simple example to add/remove multiple classes using
ng-class
Output-
Also, Read: How to use a filter in a controller?