8

I have an angular 4 web app that needs to set styles depending on the value of colors and image urls it gets from the backend. I have successfully configured the web app to use the image urls sent from the server to load the required images but the issue of the color values is more challenging. The primary colors used in a lot of places in the app are all in the styles.css file as css variables.

:root {
--grape: #4b286d;
--purple: #651f97;
--purp-button-on-hover: #6d4299;
--accessibility-green: #248700;
--green-button-on-hover: #36ad0a;
--telus-grey: #595859;
--text-grey: #54595f;
--bg-grey: #e2e2e2;
--secondary-bg: #f5f5f5;
--white: #fff;
--almost-white: #f3f3f3;
--footer-bg: #333333;
--footer-copyright: #595853;
--select-title: #4a4a4a;
--pale-grey: #f5f6f7;
--select-gradient: linear-gradient(to bottom, #f2f2f2, #d4d4d4);
--select-border: #979797;
--font-type: "Helvetica Neue", helvetica, arial, sans-serif;
--font-light: 300;
}

I want to be able, in typescript, to just change these values to the values that i get from the server when the app is loaded first. The methods that I have found seem to involve getting the HTMLElement and changing its style color to the color I want, this will mean I'd have to go through the whole app changing color for each element one at a time. Is there a better way of achieving this? thank you.

1 Answer 1

15

Since these values are defined at root level, you can just update them using document. I am not exactly sure on how you can access the document in angular, but once you have document, you can do something like this:

document.documentElement.style.setProperty(`--${your-variable}`, value + suffix); //suffix may be px or ''

This way, you will directly set the css variable which will take effect at all the places and you will not have to target individual elements.

Sign up to request clarification or add additional context in comments.

1 Comment

Works for me, amazing!

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.