what is difference between ngClass and clas binding?

Viewed 65

what is difference between ngClass and clas binding?

Both accepts same syntax. Only difference I saw was class can do this: [class.sale]="onSale".

Both accepts almost similar syntax:

[ngClass]="stringExp|arrayExp|objExp"
[class]="string | Record<string, boolean | undefined | null> | Array<string>"

I've read some answers on SO. But they are few years ago. I think now the angular team had made both expression similar.

Can someone confirm this?

2 Answers

To expand off Michael D's answer, it's a case of singular vs multiple classes.

Use of the class binding allows you to add or remove a single class at a time as you've shown in your question:

[class.sale]="onSale"
[class.error]="errors.length > 1"

ngClass on the other hand allows you to add or remove multiple classes through a single call like so:

[ngclass]="{'sale': onSale, 'error': errors.length > 1}"

With the style class appearing on the left and your expression for it on the right.

EDIT

I thought it might also be worth noting that you can also pass the classes as an object that you've defined in your component. For example, you may have the following in your component:

classes = {
    'sale': onSale,
    'error': errors.length > 1
}

You can then pass to the [ngclass] binding like so:

[ngClass]="classes"

From Angular official documentation, you can read about :

syntax [class] in order to bind class using Attribute, class, and style bindings

syntax [ngClass] in order to add css to you html elements

regarding the effect of [class.className]='booleanVariable'

it is the same as [ngClass]="booleanVariable ? 'className' : ''"

In both cases you can apply css on conditions.

Related