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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With