Reputation: 7381
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?
Upvotes: 4
Views: 1145
Reputation: 1
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
Upvotes: 0
Reputation: 73731
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.
Upvotes: 3