ngClass - vs - [attr.class] - vs - class | will attribute interpolation be deprecated and how to make this performant

Viewed 1708

I would like a class set once when the template initializes. A colleague wrote

<div [attr.class]="localVariable === 'string' ? 'class-name' : null"><div>

but this seems odd. I think I wouldn't want

[ngClass]="{'class-name': localVariable === 'string'}"

because this would run every life cycle, and I don't expect the localVariable to change dynamically during the application execution.

I prefer instead:

class="{{localVariable === 'string' ? 'class-name' : null}}"

but my colleague said that this is not advised by Angular, and that support for interpolation on attribute will be deprecated. Can anyone confirm this or make a case for which is these most performant given that the bound value is not expected to change after the template renders?

1 Answers

Using ngClass you can add classes dynamically to the current classes list for that element. But when you use attr.class it entirely reassigns the list of classes acting on that element. You can have class along with ngClass in an element where ngClass will contain the dynamic list of classes. More on ngClass here.

Related