在Angular模板HTML中使用CSS变量? [英] Using css variable in Angular template HTML?

查看:71
本文介绍了在Angular模板HTML中使用CSS变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个组件,可根据存储在json文件中的值设置div的背景颜色,然后循环浏览以显示一堆颜色样本.

I have a component that sets the background color of a div based on a value stored in a json file, which I then loop through to show a bunch of color swatches.

   <div class="color-swatch-color"
        [style.background-color]="foo"></div>

它可以很好地在变量中使用十六进制颜色: foo =#f00";

It works fine with a hex color in the variable: foo="#f00";

但是没有颜色显示我使用的颜色变量: foo ='var(-primary)';

But no color shows up what I use a color variable: foo = 'var(--primary)';

div在HTML中显示,没有引发任何错误,但div上根本没有背景色.

The div shows in the HTML, no errors are thrown, but there is no background-color at all on the div.

我应该更清楚.我有一个主题,使用的变量如--primary,--secondary(如Bootstrap).我想用这些颜色显示色板.但是,我在CSS类中使用了变量,以便可以通过body标签上的主题"类来更改其值.

I should be clearer. I have a theme that uses variables like --primary, --secondary (like Bootstrap). I want to show swatches with those colors. However, I use the variables in my CSS classes so that I can can change their value with a "theme" class on the body tag.

因此,我试图将色板设置为变量,以便当用户更改body标签上的类时,该色板会像我的应用程序的其余部分一样自动更改颜色.

So I am trying to set my swatches to the variables so that when the user changes the class on the body tag, the swatch changes color automatically like the rest of my app.

看看这个堆叠闪电战.如果我直接分配var,它将分配背景色.通过角度变量,它不会分配任何颜色.

Take a look at this stackblitz. If I assign the var directly, it assigns the background color. Via the angular variable it doesn't assign any color.

我这样做是因为,如果您打开开发工具,则可以选择我的brandcolor变量并随时对其进行更改;这类似于切换主题,其中"brandcolor"可以随主题变化

I am doing it this way because if you open dev tools, you can select my brandcolor variable and change it on the fly; this is similar to switching themes, where "brandcolor" can vary accoss themes

推荐答案

OP的stackblitz示例在有角度的编译器认为 var 是危险的事实的基础上起作用.

the OP's stackblitz example works beside the fact the var is considered dangerously by the angular compiler.

可以使用DomSanitizer绕过它

this can be bypassed with the DomSanitizer

public bg = this.sanitizer.bypassSecurityTrustStyle('var(--brandcolor)');
constructor(private sanitizer: DomSanitizer) {}

请参见 https://stackblitz.com/edit/angular-kerk9q?file = src/app/app.component.html

这篇关于在Angular模板HTML中使用CSS变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆