Angular 2+ CSS Custom Properties (variables) with Renderer

3.1k Views Asked by At

I'm trying to convert Vanilla JavaScript code to Angular 2+.

In Javascript, I have a statement like this:

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

In Angular, the only way I've found to replicate the above statement is like this:

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

The issue: If I have multiple custom properties being dynamically set at different times (--cssVariable1, --cssVariable2...). The Angular Renderer will overwrite the style property instead of appending to the style property.

Can the renderer be used to achieve this functionality? If not, is there a preferred way of using CSS custom properties in Angular? Thanks!

3

There are 3 best solutions below

0
Marko Francekovic On BEST ANSWER

What you could use is [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.

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.

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

Hope it helps.

2
David On

Try using setStyle method

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

Try using Renderer2 Object setStyle method

/**
 * 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);