首页 > 解决方案 > 如何在运行时在 Angular 组件中注入 CSS 样式表

问题描述

我需要在运行时将样式表注入到组件中。基本上根据用户配置设置选择一个主题,并依赖于 CSS url 更改的活动主题。

静态注入 viastyelUrls对此不起作用,因为它在编译时是静态的。

当我直接将样式链接注入组件时,它似乎也不起作用:

<link [href]="themeLink" rel="stylesheet"  *ngIf="themeLink" />

我在这里尝试了一些变体-插值,使用@import()样式-似乎都不适用于动态分配的值。

资源已添加到包含的资源中,如果我将上述链接硬编码为特定样式,它就可以工作。但是在运行时设置值会给我一个错误:

core.js:6228 ERROR 错误:资源 URL 上下文中使用的不安全值(请参阅http://g.co/ng/security#xss

这是公平的。

但我似乎找不到在运行时动态设置样式表的方法。

这样做的正确方法是什么?

标签: cssangularangular-components

解决方案


您可以借助DomSanitizerbypassSecurityTrustResourceUrl的方法禁用 Angular 清理来防止错误:

constructor(private sanitizer: DomSanitizer) {
  let themeUrl = "themes/" + appModel.configuration.theme + "/theme.css";
  this.themeLink = this.domSanitizer.bypassSecurityTrustResourceUrl(themeUrl);
}

推荐阅读