Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between [ngClass]/[class] and [className] in Angular 9?

Tags:

angular

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?

like image 614
Maurice Avatar asked Nov 06 '25 04:11

Maurice


1 Answers

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.

like image 146
ConnorsFan Avatar answered Nov 08 '25 00:11

ConnorsFan