Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 277
efarley Avatar asked Dec 01 '16 23:12

efarley


Video Answer


2 Answers

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>
like image 156
lthh89vt Avatar answered Sep 19 '22 21:09

lthh89vt


Maybe using a function to return the ngClass array will helps.

<li *ngFor='let tool of tools'><span [ngClass]='chkClass(tool)'>{{tool.name}}</span></li>


public chkClass(item:any){
    let newClass = {};
     newClass[item.name+ '-active'] = true;
     newClass[item.name] = false;
     return newClass;
}
like image 20
KarateJB Avatar answered Sep 18 '22 21:09

KarateJB