Angular Renderer with CSS Custom Properties (variables)

1,682 views
Skip to first unread message

Erik Verduin

unread,
Jun 14, 2018, 11:12:28 AM6/14/18
to Angular and AngularJS discussion
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 (--cssVariableName1, --cssVariableName2...). 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!

Sander Elias

unread,
Jun 14, 2018, 12:09:31 PM6/14/18
to Angular and AngularJS discussion
Hi Erik,

Perhaps using renderer2, instead of the deprecated renderer will give you a solution.
However, as this is a purely visual thing, you might consider doing direct DOM manipualtion.

class sample {
   elm
= this.elmRef.nativeElement

   constrcutor
(private elmRef:ElementRef) {}

   ngOninit
() {
       
if (this.elm) {
           
// You are in the browser, it's safe to do DOM manipulation in here.
       
}
   
}
}

If you need to do SSR, it might be worth it to dig deeper into renderer2, I think it's possible to do what you want. But manipulating styles is a tad trickier as manipulating DOM, so I'm not 100% sure it can be done with rendere2

Regards
Sander

Sander Elias

unread,
Jun 14, 2018, 12:16:47 PM6/14/18
to Angular and AngularJS discussion
I just ran into this article by Austin, might be relevant to you

Erik Verduin

unread,
Jun 14, 2018, 3:56:54 PM6/14/18
to Angular and AngularJS discussion
Hi Sander,

Thanks for the article! I gave it a look, while this is exactly the issue I was looking at, Austin seems to be directly modifying the DOM with elementRef instead of using the renderer. I'm concerned this may be dangerous as suggested by other people in the community.

Thanks!
Erik

Sander Elias

unread,
Jun 14, 2018, 10:50:07 PM6/14/18
to Angular and AngularJS discussion
Hi Erik,

N,o it's not dangerous, as long as you wrap it like I did in the code I sampled to you. Check if there is a .nativeElement. If it's there, you are in an environment where you have an actual DOM.

Regards
Sander
Reply all
Reply to author
Forward
0 new messages