Difference between [ngClass] vs [class] binding

Ben Taliadoros picture Ben Taliadoros · Jul 26, 2017 · Viewed 27.2k times · Source

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

<div [class.extra-sparkle]="isDelightful">
<div [ngClass]="{'extra-sparkle': isDelightful}">

Answer

G&#252;nter Z&#246;chbauer picture Günter Zöchbauer · Jul 26, 2017

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.