英文:
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>
英文:
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>
答案1
得分: 1
在模板中,你不能连接值,但如果 colorcode
有 red
作为默认值,你可以定义一个获取器,返回 style 属性的全部内容:
JS
get divStyle() {
return `position:auto; color ${this.colorcode}`;
}
HTML
<template if:true={bmirange1}>
<div style={divStyle}>BMI: {bmiValue}</div>
</template>
你还可以在 CSS 文件中为该颜色定义一个适当的类,并通过自定义属性(即 --bmi-color
)设置颜色:
.dynamicColor {
color: var(--bmi-color, red);
}
在 JavaScript 中,当 colorcode
属性更改时,你还需要设置此 CSS 自定义属性:
document.documentElement.style.setProperty('--bmi-color', this.colorcode);
然后你的模板将是:
<template if:true={bmirange1}>
<div class="dynamicColor" style="position:auto">BMI: {bmiValue}</div>
</template>
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论