3

There are a lot of SO questions about the difference between ngClass and class like this one:

Difference between [ngClass] vs [class] binding

But you can also use [className] as a binding. What is the difference between [ngClass] and [className] and when should you use one over the other?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Maurice
  • 6,698
  • 9
  • 47
  • 104
  • Does binding to className *do anything*, in general (i.e. where not specifically provided for by a component)? I've always used class. – jonrsharpe May 14 '20 at 22:02
  • @jonrsharpe yes it behaves exactly the same way as binding to ngClass would. Therefore i would really like to know what exactly the difference would be. – Maurice May 14 '20 at 22:05
  • Ah - [*"there is an automatic attribute-to-property mapping in Angular for several common attributes. These include class/className..."*](https://angular.io/guide/template-syntax#binding-targets) - given that's the only reference to it, I'd stick with what's [documented](https://angular.io/guide/template-syntax#class-binding). If it behaves the same way, what makes you think there's a difference? – jonrsharpe May 14 '20 at 22:05
  • @jonrsharpe so what does that mean? That `className` is nothing more then a synonym for `ngClass` ? – Maurice May 14 '20 at 22:09

2 Answers2

3

Like [className], [ngClass] allows to bind a string expression of space separated class names:

<some-element [ngClass]="'first second'">...</some-element>
<some-element [className]="'first second'">...</some-element>

But [ngClass] also allows to bind the class names as an array or as an object (where each property key is a class name which is applied or not according to the associated value):

<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': condition1, 'second': condition2}">...</some-element>

These syntaxes, which can be convenient, are not supported by [className] since className is a string property of HTML elements.

See this stackblitz for a demo.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
  • This is only true for ViewEngine. With Angular Ivy, both approach is identical https://stackblitz.com/edit/ngclass-class-ivy?file=src/app/app.component.html – Chau Tran Nov 14 '20 at 01:44
0

As @chau-tran said, they are almost identical, but. Even in Ivy I've found the case where [ngClass] is more powerful than a regular [class] binding.

You can't bind multiple classes with [class] binding like this:

<div [class]="{'class1 class2': true}"></div>

In this case, you'll get this error:

Error: Failed to execute 'add' on 'DOMTokenList': The token provided ('class1 class2') contains HTML space characters, which are not valid in tokens.

But it's totally valid with [ngClass]:

<div [ngClass]="{'class1 class2': true}"></div>

https://stackblitz.com/edit/ngclass-class-ivy-qcg3ta?file=src/app/app.component.html