I want to set style attribute value dynamically while looping in template.

But LWC is warning me of this error message.

LWC1060: Template expression doesn't allow CallExpression

Below is my template.

  <template for:each={colors} for:item="color">
    <li key={color} class="slds-color-picker__swatch" role="presentation">
      <a class="slds-color-picker__swatch-trigger" href="#" role="option" tabindex="0">
        <span class="slds-swatch" style={makeColorStyle(color)}><--! warning here -->
          <span class="slds-assistive-text">{color}</span>

How can I achieve my purpose?

  • As templates do not support an expression, you would have to add extra property on the list holding style and use it in style. – Raul Jun 25 '19 at 6:57
  • 4
    Hi @tatsuya, welcome to SFSE. Your question is possibly a duplicate of Expression Functions within Lightning Web Components. – Raul Jun 25 '19 at 8:17
  • Hi, @Raul. Thank you for your answer! I think it would be duplicate too. But I also think the information I have is not capable to reach the post. So what should I do? – tatsuya kanemoto Jun 25 '19 at 8:48

While it is possible to use this approach Expression Functions within Lightning Web Components, IMHO the cleaner approach is to have the data values directly on the object that is iterated over.

So in this case, logic could build the array or it could be hardcoded:

get colors() {
    return [
        {name: 'red', style: 'color: "#FF5733"'},
        {name: 'green', style: 'color: "#83FF33"'},

and then referenced like this:

<template for:each={colors} for:item="color">
    <li key={color.name} ...>
       <span style={color.style} ...>
       <span ...>{color.name}</span>

You can either push the calculated value in the array as @keith mentioned. However, in a more complex scenario, you could also create a child component for the iteration item. The child component would then do the processing.

  • Very neat and smart approach. Thank you! – tatsuya kanemoto Jun 25 '19 at 17:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.