Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import variables from .ts into .scss angular

I am developing an angular component and I would like to import into my scss file variables (such as colors) from my ts file and I am going throught some issues. I have seen some examples with node-sass and webpack but are not very clear to me. Thanks

like image 222
Omar Ayala Avatar asked Oct 22 '18 11:10

Omar Ayala


4 Answers

One option is CSS Variables.

This is not a SASS variable that is available in preprocessing, but rather something available in the browser during runtime. Therefore, you can get/set it with javascript, and the CSS style will update based on the variable value.

For instance, let's say your component allows you to set the text color through a javascript variable textColor:

CSS:

p { color: var(--text-color); }

JS:

element.style.setProperty("--text-color", textColor);

And if you want the flexibility/maintainability of variables in your SCSS -- you can have the variables point to the JS/CSS variables.

SCSS:

// _vars.scss
$text-color: var(--text-color);

// _styles.scss
p { color: $text-color }

Make sure to verify that this feature has the level of browser support your app needs.

like image 50
miir Avatar answered Oct 24 '22 10:10

miir


have you tried ngStyle

 <some-element [ngStyle]="{'color': styleExp}">...</some-element>

and then in your .ts

 styleExp = 'red' 

you can read more on it on the official docs https://angular.io/api/common/NgStyle

like image 24
Rogelio Avatar answered Oct 24 '22 09:10

Rogelio


It is not possible to import variables to scss files from the ts files. Instead, you can use angular angular properties ngStyle and ngClass

like image 3
Skandar B.A Avatar answered Oct 24 '22 08:10

Skandar B.A


constructor(private elem: ElementRef){
    this.colorValue = "yellow";
    this.elem.nativeElement.style.setProperty('--text-color', colorValue);
}     

then in the css or scss you can use --text-color variable

p { color: var(--text-color); }
like image 1
Mohammad Hassani Avatar answered Oct 24 '22 09:10

Mohammad Hassani