3

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!

Link79097
  • 68
  • 3
  • 6

3 Answers3

10

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);
vikey
  • 331
  • 2
  • 5
4

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.

Marko Francekovic
  • 1,450
  • 10
  • 10
0

Try using setStyle method

renderer.setStyle(document.documentElement, `--${cssVariableName}`, `${value}`);
David
  • 33,444
  • 11
  • 80
  • 118
  • 1
    setStyle adds a property to the style tag of the element and does append. However, the operation is ignored for custom properties and the property is not added. Example: `'--background', 'green' // Invalid` `'background', 'green' // Valid` – Link79097 Jun 14 '18 at 14:56
  • 2
    please see @vikey's answer below. There's a third (and optional) parameter that needs to be set to 2 for these cases. I just tested it and I can confirm it works – Jandro Rojas Mar 20 '20 at 16:56