Angular 2 how do I use a variable for the value of ngClass

efarley picture efarley · Dec 2, 2016 · Viewed 13.5k times · Source

I want to use a variable for the value of ngClass that will be added to the class list. My use case is that I have a collection of image sprites, there is the base sprite and then an active state which has the same filename as the base sprite only with '-active' added to the end. I add the sprites to the document by giving an element a class matching the desired sprites file name. I need to toggle back and forth between the two sprites when a user hovers over the element. How do I do that?

For example something like this (NOTE: tool.name === the file name of the sprite to display):

<li *ngFor='let tool of tools' (mouseenter)='tool.isActive = true' (mouseleave)='tool.isActive = false'>
  <span [ngClass]='{ {{tool.name}}-active: tool.isActive, {{tool.name}}: !tool.isActive }'>{{tool.name}}</span>
</li>

Answer

lthh89vt picture lthh89vt · Dec 2, 2016

In stead of having class .tool-name-active You can have your class as .tool-name.active Then you can do the following

<li *ngFor='let tool of tools'>
  <span class="{{tool.name}}" [ngClass]='{active: isActive}'>{{tool.name}}</span>
</li>