Is there a way to Get a variable that is set in the global scss file from a ts file in Angular (8) I'm looking to use some of the defined variables dynamically in a canvas element defined in the ts code.
4 Answers
I have a way to do this using a styles service based on https://en.programqa.com/question/52907585/
Within Global.SCSS
@mixin ExportVariables($map, $prefix: null) {
$mapPrefix: "--#{$prefix}";
@if ($prefix){
$mapPrefix: "#{$mapPrefix}-";
}
body {
@each $name, $value in $map {
#{$mapPrefix}#{$name}: $value;
}
}
}
--idle-state: #29ABE2;
// Import each of these in the theme service
$stateSCSS:(
idle: var(--idle-state),
);
@include ExportVariables($stateSCSS, 'stateSCSS');
In the Service
const bodyStyles = window.getComputedStyle(document.body);
this.stateSCSS = {
idle: bodyStyles.getPropertyValue('--stateSCSS-idle'),
};
Comments
I think this answers your questions: access SASS values ($colors from variables.scss) in Typescript (Angular2 ionic2)
TLDR:
Unfortunately, there is no way to access SASS variable directly from typescript/javascript code. However, we can make a workaround to access those variables.
You can view the workaround in the post mentioned above
Comments
As mentioned by @tgall019, CSS variables can be accessed in typescript.
within style.css
:root {
--app-color-green: green
}
in the app.component.ts
export class AppComponent {
constructor(@Inject(DOCUMENT) private document: Document) {
const greenColor = this.document.body.computedStyleMap().get('--app-color-green').toString()
console.log(greenColor)
}
}