将变量从.ts导入到.scss Angular

问题描述 投票:0回答:6

我正在开发一个角度组件,我想从我的 ts 文件导入我的 scss 文件变量(例如颜色),我遇到了一些问题。 我看过一些使用 node-sass 和 webpack 的例子,但我不太清楚。 谢谢

javascript angular typescript sass angular6
6个回答
7
投票

一个选项是CSS变量

这不是预处理中可用的 SASS 变量,而是运行时浏览器中可用的变量。因此,您可以使用 javascript 获取/设置它,并且 CSS 样式将根据变量值进行更新。

例如,假设您的组件允许您通过 JavaScript 变量设置文本颜色

textColor
:

CSS:

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

JS:

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

如果您希望 SCSS 中的变量具有灵活性/可维护性——您可以让变量指向 JS/CSS 变量。

SCSS:

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

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

确保验证此功能具有您的应用程序所需的浏览器支持级别。


4
投票

你尝试过ngStyle吗

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

然后在你的.ts中

 styleExp = 'red' 

您可以在官方文档中阅读更多相关内容 https://angular.io/api/common/NgStyle


3
投票

无法将变量从 ts 文件导入到 scss 文件。相反,您可以使用 Angular 角度属性 ngStyle 和 ngClass


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

然后在 css 或 scss 中你可以使用 --text-color 变量

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

2
投票

我知道这已经很旧了,但我想给出一个人们可能感兴趣的答案:

在 example.component.ts 中

@Component({
    selector: 'example',
    templateUrl: './example.component.html',
    styleUrls: ['./example.component.scss'],
})
export class ExampleComponent implements OnInit {
    ...
    @HostBinding('style.--nameOfVar') nameOfVar = 'red';
    ...
}

在 example.component.scss (或 css)中

.example {
    color: var(--nameOfVar);
}

0
投票
To use the variable of ts file in scss, u can simply follow this approach
You can use [style.yourVariable] in html and this variable can be referenced in scss using var(--yourVariable),make changes from ts file and it will reflect in scss like the below given code

Html:
<div class="custom-class" [style.--default-example-color]="yourVariable"</div>

enter code here
.custom-class{
        background-color: var(--default-example-color);
    }
© www.soinside.com 2019 - 2024. All rights reserved.