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!

2
  • 1
    DId you see this? stackoverflow.com/questions/48916671/… Commented Jun 14, 2018 at 16:03
  • Thanks for the link! This helps a ton, thank you! Commented Jun 14, 2018 at 20:46

3 Answers 3

11

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);
Sign up to request clarification or add additional context in comments.

2 Comments

you're a lifesaver! :D I totally missed the flag param there and wasted an hour scratching my head!
This Solution works fine for me! The flag param 2 here is important!
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.

Comments

0

Try using setStyle method

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

2 Comments

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
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.