0

I have a simple LWC component where I want users to define CSS using designer attributes. However, it doesn't seem to pick it when I load it on the page even though console logs are picking up the right value. Please help.

Here is my code: HTML:

<template>
    <div style={divStyle}>
        <span style={fontStyle}>{textToDisplay}</span>
    </div>
</template>

JS file:

import { LightningElement, api } from 'lwc';

export default class GenericCard extends LightningElement {
    @api textToDisplay;
    @api textColor;
    @api backgroundColor;
    
    get divStyle() {
        console.log('User entered background color: ' + this.backgroundColor);
        return 'background:${this.backgroundColor};color:${this.textColor};text-align:center;padding:6px;';
    }

    get fontStyle() {
        return 'color:${this.textColor}';
    }
}

I can see text align and padding but not the background color for the div or the font color.

2 Answers 2

3

It looks like you are trying to use JavaScript String Interpolation but with a different quote. Try using back tick (`) instead of single quote (').

I tried the following in console

function SampleClass() {
    this.name = 'Ant'
}
SampleClass.prototype.getNameString = function() {
   return `My name is ${this.name}`;
} 

var inst = new SampleClass();
inst.getNameString();

Screenshot with result of running the code

You can refer to https://dmitripavlutin.com/string-interpolation-in-javascript/ or any other article for more detail

1

Your issues is with the concatenation of the style strings.

Try this - it worked for me in a playground:

get divStyle() {
    console.log('User entered background color: ' + this.backgroundColor);
    return 'background:' + this.backgroundColor
    +';color:' + this.textColor + ';text-align:center;padding:6px;';
}

get fontStyle() {
    return 'color:' + this.textColor + ';';
}

You must log in to answer this question.

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