javascripthtmlwebsalesforcelwc

How to pass values from JS to HTML tags in lightning web component?


I am trying to pass color to the existing style of HTML tag from Javascript. However, it's not working as I am trying. Please help.

Actual HTML

<template if:true={bmirange1}>
    <div style="color: red; position:auto">BMI: {bmiValue}</div>
</template>

What I am trying

<template if:true={bmirange1}>
    <div style="color:"{colorcode}"; position:auto">BMI: {bmiValue}</div>
</template>

Solution

  • You cannot concatenate values in the tempate, but if colorcode has red as default value, you could define a getter that returns the whole content of style attribute:
    JS

    get divStyle() {
        return `position:auto; color ${this.colorcode}`;
    }
    

    HTML

    <template if:true={bmirange1}>
        <div style={divStyle}>BMI: {bmiValue}</div>
    </template>
    

    You could also define an appropriate class for that color in the CSS file and set the color via a custom property (i.e. --bmi-color):

    .dynamicColor {
         color: var(--bmi-color, red);
    }
    

    In the JS, when the colorcode property changes, you will have to set this css custom property too:

    document.documentElement.style.setProperty('--bmi-color', this.colorcode);
    

    Then your template would be

    <template if:true={bmirange1}>
        <div class="dynamicColor" style="position:auto">BMI: {bmiValue}</div>
    </template>