Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between [ngClass] vs [class] binding

What is the difference in Angular 2 between the following snippets:

<div [class.extra-sparkle]="isDelightful"> <div [ngClass]="{'extra-sparkle': isDelightful}"> 
like image 667
Ben Taliadoros Avatar asked Jul 26 '17 08:07

Ben Taliadoros


People also ask

What is the difference between NgClass and NgStyle?

ng-style is used to interpolate javascript object into style attribute, not css class. And ng-class directive translates your object into class attribute.

Can we use NgClass and class together?

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.

What is NgClass used for?

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.

Is NgClass a directive?

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

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.

like image 189
Günter Zöchbauer Avatar answered Oct 17 '22 00:10

Günter Zöchbauer