简体   繁体   中英

Angular 9 / Material - Reuse of material theme variables in angular components style

I have standard angular 9 application with material theming. We experienced the problem of increased bundles sizes and found out that our reuse of scss styles causes this increase. The issue was that imported scss was compiled in the component as stated in this blog .

Initial we wanted to reused the material theming variables as follows in our angular components

@import './theme.scss';

test{ background-color: mat-color($app-primary) }

To tackle this issue we followed the blogs .advice to move such code as either global style or using sass mixins. We implemented the sass-mixins as followed and reused it in our component styles:

@mixin primary-background-color {
  background-color: mat-color($app-primary);
}
@import 'mixins.scss'
  .test {
    @include primary-background-color;
  }

Nevertheless, following this advice the bundle sizes decreased a little bit by using sass-mixins, but not as much as we would move the entire code to gobal style.

This leads so my question: Is there a recommended usage of reuse material theme colours in components styles? I cannot believe that the "solution" for my problem is moving the component styles to global style!?

Looking forward to helpfull anwsers! Cheers!

I got the same problem but already fixed.

I think the best solution is this one Link

What I also add in my theme, a background variable to be possible reuse in different components like the image below..

Theme

You can do this in a different way:

There are something called 'partials'. You can create partials for various things and include/import them in your component.scss file and use them

Example:

At your root level, create a folder called styles. Inside styles, you can create multiple partials, one for variables, one for mixins, one for fonts etc.,

Partials start with an underscore for their file name such as _variables.scss, _mixins.scss, etc. The underscore will prevent the angular compiler from compiling everytime.

In '_variables.scss' file, you can create multiple global variables for colors, such as 

$primary-color: #fff;
$secondary-color: #333; etc

In '_mixins.scss' you can create mixins such as 
@mixin mixin-name() {
  mixins functionality
}


In your component.scss file, simply import them and use it. 

component.scss

@import '../styles/mixins';
@import '../styles/variables';

.component-class-name {
 background-color: $primary-color;
 color: $secondary-color;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM