css - 如何在运行时在 Angular 组件中注入 CSS 样式表
问题描述
我需要在运行时将样式表注入到组件中。基本上根据用户配置设置选择一个主题,并依赖于 CSS url 更改的活动主题。
静态注入 viastyelUrls
对此不起作用,因为它在编译时是静态的。
当我直接将样式链接注入组件时,它似乎也不起作用:
<link [href]="themeLink" rel="stylesheet" *ngIf="themeLink" />
我在这里尝试了一些变体-插值,使用@import()
样式-似乎都不适用于动态分配的值。
资源已添加到包含的资源中,如果我将上述链接硬编码为特定样式,它就可以工作。但是在运行时设置值会给我一个错误:
core.js:6228 ERROR 错误:资源 URL 上下文中使用的不安全值(请参阅http://g.co/ng/security#xss)
这是公平的。
但我似乎找不到在运行时动态设置样式表的方法。
这样做的正确方法是什么?
解决方案
您可以借助DomSanitizerbypassSecurityTrustResourceUrl
的方法禁用 Angular 清理来防止错误:
constructor(private sanitizer: DomSanitizer) {
let themeUrl = "themes/" + appModel.configuration.theme + "/theme.css";
this.themeLink = this.domSanitizer.bypassSecurityTrustResourceUrl(themeUrl);
}
推荐阅读
- docker - 使用 dockerfile 构建 Rust Cross
- javascript - 单个元素的等效 d3js selection.each()
- flask - Flask-Socket-IO 面板
- mysql - MySQL - 优化 JOIN 只对必要的行进行分组
- javascript - 将字符串转换为 JavaScript 对象
- java - 如何在流中返回 void?
- jquery - boostrap-datepicker:如何消除更改效果?
- ios - Flutter:如何显示来自 Firebase 的文本?
- spring - 使用 Criteria API Pageable 的内存泄漏
- c++ - 如何使用 QTimeLine 类在 C++ 中重写 QML 时间线?