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>
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>
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With