Exporting SCSS variables for accessing at script code level
#

If working with angular, you have to decide during the creation of the application, which stylesheet format you want to use. I mostly use SCSS (SASS – Syntactically Awesome Style Sheets) because I feel very comfortable with it. Also I feel like it has the most useful features and built-in options.

During my work I came across a problem. I needed to access colors from my TypeScript files, which were defined as SCSS variables in my stylesheet. So I’ve searched for a good, simple solution.

Exporting variables from SCSS stylesheet
#

The main element of this blog post is to make SCSS variables, which are defined like the following example, public accessible on a global element at the HTML code. This can be done in the body-element.

1
$myCustomVariable: #424242;

After we defined anywhere in our SCSS stylesheet this variable, we are working with two custom SCSS functions.

styles.scss

You should use the define-custom-property($name, $value) which accepts 2 parameters to define a new custom variable for export. Property $name defines the variable name in the body tag and $value its value.

In the body tag we can call this function to export our defined myCustomVariable :

1
@include define-custom-property(myCustomVariable, $myCustomVariable);

Now the variables should be appended to the body tag in our HTML page.

Style of the HTML body tag
Style of the HTML body tag

Accessing css styles from script source code
#

At the script language level there is a method called getComputedStyle at the window property, which should be accessible via a custom component, the app component or wherever you want to access the variable in code.

So we have to read out the “computed” styles from the document body and read out the property value by name:

This can then be wrapped by a very simple custom component, which provides us with a method.

sass-helper.ts

The written component can then be included in the base of the application like the body tag or something else, viewed and accessed via a ViewChild call:

1
@ViewChild(SassHelperComponent) private sassHelper: SassHelperComponent;

and then used with a simple method:

1
const myCustomVariable = this.sassHelper.readProperty('myCustomVariable');

Conclusion
#

Special thanks to Mete Cantimur, who animated me with his good contribution on Stack Overflow post here, to do this blog post.