Skip to main content

Angular: Access CSS Variables

CSS Variables can be defined in css (or SCSS) like this:

NOTE: These are defines in the root element, in the styles.scss file of an app.

:root {
    --sidenav-width: 300px;
    --sidenav-collapsed-width: 50px;
    --sidenav-background-color: var(--app-background-color);
    --sidenav-text-color: var(--app-text-color);
    --sidenav-transition-duration: 400ms;
    --app-background-color: #b6b9bd;
    --app-text-color: #282828;
}

The above defines several global CSS variables (root scoped).
It as well, shows how to define a variable that takes the value of another.

Reading

Here's how we can access these global CSS variables from an Angular component:

const sidenavTransitionDurationFromCssVariable =
        getComputedStyle(document.body)
        .getPropertyValue('--sidenav-transition-duration');

let dur = parseInt(sidenavTransitionDurationFromCssVariable, 10);

The above code snippet retrieves a global CSS variable called, sidenav-transition-duration, from the DOM, and parses it into an integer (with a default value, if not found).

This allows an Angular component to use data stored in CSS.

Writing

Here's how to write a new value to the same global CSS variable from an Angular component:

document.documentElement.style
    .setProperty('--sidenav-transition-duration', '300');

The above statement writes a '300' to the transition duration variable that is at :root scope of the DOM.

NOTE: All writes to variables are as strings, so you will have to convert to string before the setProperty call.