Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you access Angular scss variables in typescript? [duplicate]

In Ionic 2, I would like to access the $colors variables from the file "[my project]\src\theme\variables.scss".

This file contains:

$colors: (
  primary:    #387ef5,
  secondary:  #32db64,
  danger:     #f53d3d,
  light:      #f4f4f4,
  dark:       #222,
  favorite:   #69BB7B
);

In a component, I draw a canvas. It looks like that:

import {Component, Input, ViewChild, ElementRef} from '@angular/core';

@Component({
    selector: 'my-graph',
})
@View({
    template: `<canvas #myGraph class='myGraph'
     [attr.width]='_size'
     [attr.height]='_size'></canvas>`,
})

export class MyGraphDiagram {
    private _size: number;

    // get the element with the #myGraph on it
    @ViewChild("myGraph") myGraph: ElementRef; 

    constructor(){
        this._size = 150;
    }

    ngAfterViewInit() { // wait for the view to init before using the element

      let context: CanvasRenderingContext2D = this.myGraph.nativeElement.getContext("2d");
      // HERE THE COLOR IS DEFINED AND I D LIKE TO ACCESS variable.scss TO DO THAT
      context.fillStyle = 'blue';
      context.fillRect(10, 10, 150, 150);
    }

}

As one can see, at some point in this code the color of the shape is defined: context.fillStyle = 'blue' , I would like to use instead something like context.fillStyle = '[variables.scss OBJECT].$colors.primary '.

Has anyone an idea?

like image 455
nyluje Avatar asked Nov 04 '16 09:11

nyluje


People also ask

How do I use SCSS variables in Typescript?

Create a new React Project with Typescript and scss Ok, fine you have your React app with Typescript, now we will add “sass” as node-sass is now deprecated, rename the basic css file. Rename all index. css into index. scss, update as well other files and import statements in all concerned files.

How do I change dynamic variables in SCSS?

SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time. However, CSS variables just sits there during run time, and you can dynamically CRUD them during run time with JavaScript (Web API).

Is sass the same as SCSS?

SASS (Syntactically Awesome Style Sheets) is a pre-processor scripting language that will be compiled or interpreted into CSS. SassScript is itself a scripting language whereas SCSS is the main syntax for the SASS which builds on top of the existing CSS syntax.


1 Answers

This is possible using CSS Modules.

CSS Modules

From the project description:

When importing the CSS Module from a JS Module, it exports an object with all mappings from local names to global names.

In a way that we could read variables from css/scss file like this:

import styles from "./style.css";    

element.innerHTML = '<div class="' + styles.className + '">';

Support for CSS Modules is already setup by default by the Angular CLI which uses Webpack configured with the css-loader.

The steps to make it work are:

  1. Export only the scss variables that you want to use.
  2. Configure a typescript module for styles.scss.
  3. Import the variables in your typescript components.

1 - Export the variables

In your styles.scss, use the keyword :export to export $colors. It seems that :export doesn't support exporting maps, only strings, so we have to create a mixin to convert a map into strings:

$colors: (
  primary: #387ef5,
  secondary: #32db64,
  danger: #f53d3d,
  light: #f4f4f4,
  dark: #222,
  favorite: #69bb7b,
);

@mixin rule($key, $value, $prefix) {
  #{$prefix}-#{$key}: $value;
}
@mixin map-to-string($map, $prefix) {
  @each $key, $value in $map {
    @include rule($key, $value, $prefix);
  }
}

:export {  
  @include map-to-string($colors, "colors");
}

The generated :export will be:

:export {
  "colors-danger": "#f53d3d";
  "colors-dark": "#222";
  "colors-favorite": "#69bb7b";
  "colors-light": "#f4f4f4";
  "colors-primary": "#387ef5";
  "colors-secondary": "#32db64";
}

2 - Configure a typescript module for styles.scss

We have to create a styles.scss.d.ts file with the following content to allow the import of styles.scss in our typescript files:

export interface globalScss {}

export const styles: globalScss;

export default styles;

3 - Import the variables in the target typescript component

As we used a default export, we could import it in our component like this:

//...
import styles from 'src/styles.scss';

@Component({
  selector: 'app-colors-use',
  templateUrl: './colors-user.component.html',
  styleUrls: ['./colors-user.component.scss'],
})
export class ColorsUserComponent implements OnInit {

  buttonColor = styles["colors-primary"] //"#387ef5"

4 - (Plus) Add type definition to styles.scss.d.ts

You could add type information to style.scss.d.ts:

export interface globalScss {  
  "colors-danger": string
  "colors-dark": string
  "colors-favorite": string
  "colors-light": string
  /**
   * Used for app-button, usually blue
   */
  "colors-primary": string
  /**
   * Used for borders, usually green
   */
  "colors-secondary": string
}

export const styles: globalScss;

export default styles;

In that way, you could have some benefits in an editor like VS code:

Comments

Auto complete

UPDATE:

The configuration above only works until ng 10. Css Modules configuration has changed considerably from ng 10 to ng 11.

like image 73
tiagolisalves Avatar answered Oct 10 '22 23:10

tiagolisalves