Set CSS class dynamically in Lightning web component

How would I translate that from Aura to LWC?

<aura:iteration items="{!v.contacts}" var="contact">
   <div class="{!contact.isActive ? 'slds-tabs--path dimmed' : 'slds-tabs--path'}">...</div>
</aura:iteration>

Answer

The documentation covers this explicitly:

To compute a value for a property, use a JavaScript getter. For example, to convert the name to all uppercase letters, use a getter function in the JavaScript class, not an expression in the template.

Getters are much more powerful than expressions because they’re JavaScript functions. Getters also enable unit testing, which reduces bugs and increases fun.

Your example code would look like this:

<!-- MyComponent.html -->

<div class={tabClass}>
// MyComponent.js

get tabClass() { 
  return this.active ? 'slds-tabs--path dimmed' : 'slds-tabs--path';
}

Your concerns about separating UI from controller logic do not apply here as this is not a “controller”. That MVC pattern is an Aura-ism. This is the code which drives your component’s functionality so it makes sense that your JS would know about class names.

Edit:

After you changed your question, I think the best way to do what you’re trying to do is to have a custom “contact” component which when clicked, becomes active, and has an

@api active;

property, which you can call from the parent. In your comments below you say this is too much overhead, but this is the proper way to do this if you wish to manage the state of the contact. In your code example you are only toggling one class, but in a real world scenario there are many different things which you might want to change about a contact and having many expressions makes the code harder to read and harder to test.

For most list items the suggestion is to have an individual element for each list item like so:

<c-list>
  <c-list-item></c-list-item>
  <c-list-item></c-list-item>
  <c-list-item></c-list-item>
</c-list>

Attribution
Source : Link , Question Author : Robert Sösemann , Answer Author : Community

Leave a Comment