Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global scss variables for Angular components without importing them everytime

I do already have SCSS variables defined in src/styles/settings/_variables.scss and I am importing them into src/styles.scss, but still these variables aren't available for every single component.

Is there any way to make a global file which holds all SCSS variables for the rest of my components? Because writing @import in every single component .scss file it is very frustrating, especially if I have many nested components.

I know, there is a lot of similar questions, but it seems like they're all outdated and do not relate to the recent versions of Angular.

I use Angular 7.3 with CLI.

like image 556
Vladimir Humeniuk Avatar asked Mar 12 '19 22:03

Vladimir Humeniuk


People also ask

Can you change SCSS variable value dynamically?

CSS Variables to the Rescue CSS variables is a standard which enables you to have variables in CSS. SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time.

Can I use SCSS variables in styled components?

In SCSS, you can use variables and formulas for expressing colors, font sizes, widths and spacing variants. However, when you switch from SCSS to styled components, the syntax isn't valid anymore. Styled component files are CSS-in-JS, so they are actually JavaScript files.


1 Answers

You just need to add a little more config, so where you are declaring your global variables, you need to wrap it up in :root{}. So in src/styles/settings/_variables.scss.

:root  { --blue: #00b; // or any global you wish to share with components  } 

Then when you use them in the SCSS you will need to access them like so.

.example-class {   background-color: var(--blue) } 

To add to this regarding comments, this method can use mixins, @media and keyframes and is not limited to just colours / font. That was an example.

From my understanding you need a global file src/assets/style/global and then to import each scss file into there where you are defining them like so.

@import 'filename'; 

If you dont want global variables to be used in within a component look when you have the globals working. Look into ViewEncapsulation, as this can be used to ignore them.

like image 190
Dince12 Avatar answered Sep 21 '22 19:09

Dince12