简体   繁体   English

带有渲染器的 Angular 2+ CSS 自定义属性(变量)

[英]Angular 2+ CSS Custom Properties (variables) with Renderer

I'm trying to convert Vanilla JavaScript code to Angular 2+.我正在尝试将 Vanilla JavaScript 代码转换为 Angular 2+。

In Javascript, I have a statement like this:在 Javascript 中,我有这样的声明:

document.documentElement.style.setProperty(`--${cssVariableName}`, value);

In Angular, the only way I've found to replicate the above statement is like this:在 Angular 中,我发现复制上述语句的唯一方法是这样的:

renderer.setProperty(document.documentElement, 'style', `--${cssVariableName}: ${value}`);

The issue: If I have multiple custom properties being dynamically set at different times (--cssVariable1, --cssVariable2...).问题:如果我在不同时间动态设置多个自定义属性(--cssVariable1、--cssVariable2...)。 The Angular Renderer will overwrite the style property instead of appending to the style property. Angular Renderer 将覆盖 style 属性而不是附加到 style 属性。

Can the renderer be used to achieve this functionality?渲染器可以用来实现这个功能吗? If not, is there a preferred way of using CSS custom properties in Angular?如果没有,是否有在 Angular 中使用 CSS 自定义属性的首选方法? Thanks!谢谢!

Try using Renderer2 Object setStyle method尝试使用Renderer2 Object setStyle方法

/**
 * Implement this callback to set a CSS style for an element in the DOM.
 * @param el The element.
 * @param style The name of the style.
 * @param value The new value.
 * @param flags Flags for style variations. No flags are set by default. enum: 1 or 2, 1: Marks a style as important.   2: Marks a style as using dash case naming (this-is-dash-case).
 */
abstract setStyle(el: any, style: string, value: any, flags?: RendererStyleFlags2): void;

You need this你需要这个

 renderer.setStyle(document.documentElement, `--${cssVariableName}`, `${value}`, 2);

What you could use is [ngStyle].您可以使用的是 [ngStyle]。 You don't need to use the renderer.您不需要使用渲染器。

In your controller you can have an object with the css properties you want to apply.在您的控制器中,您可以拥有一个具有您想要应用的 css 属性的对象。

Like this.像这样。

props = {'color': 'red', 'font-size': '18px'};

And then in your html you can use that inside ngStyle to apply those properties to an element.然后在您的 html 中,您可以在 ngStyle 中使用它来将这些属性应用于元素。

<div [ngStyle]="props">Great example</div>

Hope it helps.希望能帮助到你。

尝试使用setStyle方法

renderer.setStyle(document.documentElement, `--${cssVariableName}`, `${value}`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM