3

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 4

5

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'),
};
Sign up to request clarification or add additional context in comments.

Comments

1

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

1

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)
  }
}

Comments

0

For those looking to do this without using SASS, you can try this:

getComputedStyle(document.documentElement).getPropertyValue(--your-variable)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.