如何将值从JS传递给闪电网络组件中的HTML标记?

huangapple go评论83阅读模式
英文:

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

&lt;template if:true={bmirange1}&gt;
	&lt;div style=&quot;color: red; position:auto&quot;&gt;BMI: {bmiValue}&lt;/div&gt;
&lt;/template&gt;

What I am trying

&lt;template if:true={bmirange1}&gt;
	&lt;div style=&quot;color:&quot;{colorcode}&quot;; position:auto&quot;&gt;BMI: {bmiValue}&lt;/div&gt;
&lt;/template&gt;

答案1

得分: 1

在模板中,你不能连接值,但如果 colorcodered 作为默认值,你可以定义一个获取器,返回 style 属性的全部内容:
JS

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

HTML

&lt;template if:true={bmirange1}&gt;
    &lt;div style={divStyle}&gt;BMI: {bmiValue}&lt;/div&gt;
&lt;/template&gt;

你还可以在 CSS 文件中为该颜色定义一个适当的类,并通过自定义属性(即 --bmi-color)设置颜色:

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

在 JavaScript 中,当 colorcode 属性更改时,你还需要设置此 CSS 自定义属性:

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

然后你的模板将是:

&lt;template if:true={bmirange1}&gt;
    &lt;div class=&quot;dynamicColor&quot; style=&quot;position:auto&quot;&gt;BMI: {bmiValue}&lt;/div&gt;
&lt;/template&gt;
英文:

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

&lt;template if:true={bmirange1}&gt;
    &lt;div style={divStyle}&gt;BMI: {bmiValue}&lt;/div&gt;
&lt;/template&gt;

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(&#39;--bmi-color&#39;, this.colorcode);

Then your template would be

&lt;template if:true={bmirange1}&gt;
    &lt;div class=&quot;dynamicColor&quot; style=&quot;position:auto&quot;&gt;BMI: {bmiValue}&lt;/div&gt;
&lt;/template&gt;

huangapple
  • 本文由 发表于 2023年3月31日 18:39:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75897577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定