0

I have an array stored in javascript which has data and corresponding colors to be applied to the rows in html file.

result 
{listFloors: Array(3)
listFloors: Array(3)
0:
floorNumber: 3
size: 300
spaces: Array(1)
0: {color: "#FCDFFF", residentialSpace: {…}, size: 300, width: "20px"}

I want to use the color variable to set the background color of each row along with data.I have tried using the below: style="background-color:{!spaces.color};">

1 Answer 1

1

In the case of having just one row, you'd need to use a getter:

get backgroundColor() {
    return `background-color:"${result.spaces[0].color}"`;
}

And then reference it on the markup:

style={!backgroundColor}

You're saying you have several rows, so maybe you could compute all the background-color properties to apply, and store them in the array you iterate:

// When you receive your results array
result.spaces.map(space => { space.computedBackgroundColor = `background-color:${space.color}`});

And then in your template:

<template for:each={result.spaces} for:item="space">
    <div class="row" style={space.computedBackgroundColor}>
</template>
5
  • when I am using style={!space.computedBackgroundColor}, it says Template expression doesn't allow UnaryExpressionlwc. Also I have all the computed data in my array along with the color to be applied. Feb 2, 2021 at 12:02
  • I mixed up aura and lwc syntax, try now
    – Alba Rivas
    Feb 2, 2021 at 12:11
  • Hi, I have applied the below code: for(let i=0;i<result.listFloors.length;i++) { this.computedBackgroundColor=result.listFloors[i].spaces.map(space =>{ space.color = background-color:${space.color}}); console.log('computedBackgroundColor',JSON.stringify(this.computedBackgroundColor)); } but getting error:TypeError: Cannot assign to read only property 'color' of object '#<Object>' at eval (stackingPlan.js:4) at Array.map (<anonymous>) at eval (stackingPlan.js:4) Feb 5, 2021 at 9:56
  • Also <template for:each={floors.spaces} for:item="spaces" > <td key={spaces.Id} style={spaces.computedBackgroundColor}> this is not working error:at rule or css expected Feb 5, 2021 at 10:03
  • Maybe you need background-color:"${result.spaces[0].color}";, with the "?
    – Alba Rivas
    Feb 5, 2021 at 11:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .