What is the difference in Angular 2 between the following snippets:
<div [class.extra-sparkle]="isDelightful"> <div [ngClass]="{'extra-sparkle': isDelightful}">
ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute.
yes , you can do it. Did you try it? What happened? 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.
Definition and Usage. 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.
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.
This is special Angular binding syntax
<div [class.extra-sparkle]="isDelightful">
This is part of the Angular compiler and you can't build a custom binding variant following this binding style. The only supported are [class.xxx]="..."
, [style.xxx]="..."
, and [attr.xxx]="..."
ngClass
is a normal Angular directive like you can build it yourself
<div [ngClass]="{'extra-sparkle': isDelightful}">
ngClass
is more powerful. It allows you to bind a string of classes, an array of strings, or an object like in your example.
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