Home > Enterprise >  Access SCSS variable from TypeScript
Access SCSS variable from TypeScript

Time:01-15

I'm creating a custom directive in Angular. I have a SCSS file with variables, like the image below, which I would like to import to my directive (.directive.ts). How can I do that?

variables.scss

chip.directive.ts

Thanks

CodePudding user response:

  1. Write them to custom CSS variables (you can use @each rule for lists):
:root {
  --bs-light: #f1f2f3;
  --bs-dark: #3e3e3c;
}
  1. Use this code to read variables from the document:
export enum ScssVariables {
    Light = "light",
    Dark = "dark",
}

@Directive({
    selector: "[test-attr]",
})
export class TestDirective {
    public styles: { [key in ScssVariables]: string | null } = {
        light: null,
        dark: null,
    };

    constructor() {
        const styles = window.getComputedStyle(document.body);
        Object.keys(this.styles).forEach((key: ScssVariables) => {
            this.styles[key] = styles.getPropertyValue("--bs-"   key);
        })
        console.log(this.styles);
    }
}
  •  Tags:  
  • Related