首页 > 解决方案 > Angular:以编程方式设置复杂 CSS 选择器的样式

问题描述

我正在寻找一种以编程方式执行以下操作的方法:

tr.product-row:not(.expanded-row):active {
   background-color: red; <--this part will be calculated in my .ts file
}

原因是我希望活动颜色是不同元素颜色的较浅版本。我可以计算出我需要的颜色,但不知道如何设置。

可以用 Renderer2 完成吗?

标签: angularrenderer

解决方案


使用可以在模板中绑定的 CSS 变量怎么样:

CSS:

tr.product-row:not(.expanded-row):active {
   background-color: var(--some-var); // specify some variable
}

模板:

<!-- bind to that variable using directive against component property -->
<div [style.--some-var]="theVariableInComponentFile">foobar</div>

这是一个绑定到 CSS 变量的示例。

希望这会有所帮助!


推荐阅读