Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS, difference between ng-class and class with angular expression?

What is the difference between the following two code snippets,
Code 1:

<div class={{getClass()}}/>

Code 2:

<div ng-class=getClass()/>
like image 866
vivek_jonam Avatar asked Jul 04 '14 16:07

vivek_jonam


People also ask

What is the difference between NgClass and class?

ngClass is more powerful. It allows you to bind a string of classes, an array of strings, or an object like in your example. The above two lines of code is with respect to CSS class binding in Angular. There are basically 2-3 ways you can bind css class to angular components.

What is NgClass in angular?

AngularJS ng-class Directive 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.

Can I use both class and NgClass?

You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally. This is a beginner question with no reference/guidance to this being a duplicate.

Why do we use NgClass?

The ngClass directive allows you to dynamically set CSS classes on an HTML element by databinding an expression that represents all classes to be added.


1 Answers

With the first example before angular loads your class will literally be "{{getClass()}}". While in the second example the div won't have a class until angular runs its first digest.

There might be some minor differences with when they are recalculated but Angular will keep both up to date. I've run into issues before using the first method with Animation as ng-class has some hooks into animation.

like image 176
rob Avatar answered Oct 14 '22 21:10

rob