What is the difference between the following two code snippets,
Code 1:
<div class={{getClass()}}/>
Code 2:
<div ng-class=getClass()/>
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With