【问题标题】:How to inject a CSS StyleSheet at runtime in an Angular Component如何在运行时在 Angular 组件中注入 CSS 样式表
【发布时间】:2020-11-10 05:10:32
【问题描述】:

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

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

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

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

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

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

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

这是公平的。

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

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

【问题讨论】:

  • 你尝试绑定DomSanitizer.bypassSecurityTrustResourceUrl(themeLink)的结果了吗?
  • 不-不知道那是一回事。现在检查。谢谢!是的,这行得通。想把它作为答案发布吗? this.themeLink = this.sanitizer.bypassSecurityTrustResourceUrl("themes/" + appModel.configuration.theme + "/theme.css");

标签: css angular angular-components


【解决方案1】:

您可以通过在DomSanitizerbypassSecurityTrustResourceUrl 方法的帮助下禁用Angular 清理来防止错误:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多