angular - Angular 从组件内部更改 styleUrls 值
问题描述
我正在尝试允许用户在运行时更改 styleUrls 值,所以我尝试这样做:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
// styleUrls: [ './app.component.css' ]
styleUrls: [styleUrl]
})
export class AppComponent implements OnInit {
styleUrl = './app.component.css'
ngOnInit() {
this.styleUrl = './another.css';
}
}
这不起作用,所以有可能得到这样的东西吗?
如果有怎么办?
解决方案
你想要的可以实现,但不是这样。
虽然您可以指定文件并在运行时更改它们,但使用Reflect Metada Api,这是相当先进的事情,可能会导致 Angular 出现其他问题。
如果您只想更改单个组件的样式,可以使用两个 scss 文件和一个HostBinding
.
这是一个例子:
零件
@Component({
selector: 'my-app',
templateUrl: '<button (click)="changeStyle()">Change Style</button>',
styleUrls: [ './app-one.component.scss', './app-two.component.scss' ]
})
export class AppComponent implements onInit {
@HostBinding('class') css: string = undefined;
ngOnInit(): void {
this.changeStyle();
}
changeStyle(): void {
if (/* condition */) {
// custom behaviour here
this.css = 'active';
} else {
// custom behaviour here
this.css = undefined;
}
}
}
AppOne CSS
:host.active {
button {
background-color: red;
}
}
AppTwo CSS
:host:not(.active) {
button {
background-color: blue;
}
}
请注意,我声明了两个 scss 文件,一个用于我想要的每种自定义 scss。我还使用HostBinding装饰器来触发激活的样式。
我不更改运行时文件,而是使用 css 特定性规则来仅应用我想要的 css。这是使用:not()
伪选择器完成的,您可以在此处阅读。
我还要补充一点,虽然这是在给定组件中实现更改样式的可行方法,但如果您想要实现,还有许多其他更好的方法可以在 Angular 应用程序中实现主题等。
推荐阅读
- aws-lambda - 如何在 AWS SAM 中指定映射模板
- getstream-io - 如何在所有用户之间设置共享提要?
- git - 将 Mercurial 存储库移动到现有 git 存储库的子目录中
- javascript - 结合使用 delay(0) 和 refCount()
- javascript - 在 div 和他的所有孩子中搜索文本
- java - spring boot:如何仅在 jenkins 上运行测试类?
- python - 并行循环中的引用迭代器
- excel - 日期格式的 Oracle SQL DB 导入 Excel 问题
- c# - 从基于 SQL Server 的代码优先 EF 迁移到 SQLite EF
- c# - 使用 docfx 从 Visual Studio 生成 pdf 文档会引发错误:“wkhtmltopdf 是生成 PDF 时的先决条件”