Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include SASS variables in an Angular 2 component

I'm wondering if i can use sass variables in an Angular 2 component. Something like:

@Component({

  selector: 'my-component',

  template: `
    <div>
      <div class="test-div">test div 1</div>
    </div>
  `,

  styles: [
    `
    @import "variables";

    .test-div{
      border: 1px solid $test-color;
    }
  `]

})

my file _variables.scss:

$test-color: green !default;

It seems whatever I try the sass variables aren't recognised. Any help much appreciated.

like image 281
TimFelix Avatar asked Nov 24 '16 19:11

TimFelix


1 Answers

I disagree with the correct answer here is why.

ATM correct answer suggests creating a _variables.scss on each component folder where the variables are needed. This will be very to hard to maintain in any size project unless you have a single component in which case you won't need to import; just use component.scss

There is an option in .angular-cli.json(angular.json in Angular 6), which intends to solve this exact problem, here it is:

...
,
"stylePreprocessorOptions": {
  "includePaths": [
    "./scss/base"  // BASE SCSS LOCATION
  ]
},
...

The base scss location relative path to the current file(.angular-cli.json) in that location you can add _variables.scss _mixins.scss _anyother.scss

Then in any component.scss you can:

@import 'variables';

Thanks for your time.

Extra: By your example, it seems you not using angular/cli to generate components, if that is the case use this ng g c component-name-here.

like image 118
T04435 Avatar answered Oct 20 '22 20:10

T04435