top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is ngClass directive in AngularJS?

+2 votes
357 views
What is ngClass directive in AngularJS?
posted Aug 24, 2017 by Jdk

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

AngularJS help us create interactive applications. They provide things called directives in order to change the DOM and attach specific Angular behaviors to an element we specify.

ngClass directive : This directive lets us do things like,

Add/Remove classes based on Angular variables.

Add/Remove classes based on evaluated expressions.

Bind single or multiple classes based on dynamic data.

Some Points about ng-class:

The ng-class directive dynamically binds one or more CSS classes to an HTML element.

The value of the ng-class directive can be a string, an object, or an array.

If it is a string, it should contain one or more, space-separated class names.

As an object, it should contain key-value pairs, where the key is a Boolean value, and the value is the class name of the class you want to add. The class will only be added if the key is set to true.

Examples

Ex 1:

<div ng-class="{class1 : expression1, class2 : expression2}">  

Hello World!  

</div >   

Here class1 will apply if the expression1 is true and class2 will apply if the expression2 is true.

Ex 2:

< div ng-class="{class1 : expression1, class2 : expression1}">  

Hello World!  

</div >

Here class1 and class2 will apply if the expression1 is true.

We can reduce the above code into,

< div ng-class="{'class1 class2' : expression1}">  
Hello World!  

< /div >  

Ex 3:

< div data-ng-class="expression1 && 'class1' || 'class2'">  

Hello World!  

</div >  

Here class1 will apply if the expression1 is true, otherwise class2 will apply.

answer Sep 26, 2017 by Manikandan J
...