Rick Strahl
Rick Strahl

Reputation: 17651

How to inject a CSS StyleSheet at runtime in an Angular Component

I need to inject a stylesheet into a component at runtime. Basically depending on user configuration settings a theme is picked and dependending on the active theme the CSS url changes.

Static injection via styelUrls doesn't work for this since that's static at compile time.

Nor does it seem to work when I directly inject the style link into the component:

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

I've tried a few variations here - interpolation, using an @import() style - none of it seems to work with a dynamically assigned value.

The resources have been added to the included resources and it works if I hardcode the above link to a specific style. But setting the value at runtime gives me an error:

core.js:6228 ERROR Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)

which is fair.

But I can't seem to find a way to dynamically set a style sheet at runtime.

What's the correct way to do this?

Upvotes: 3

Views: 3319

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73731

You can prevent the error by disabling the Angular sanitization with the help of the bypassSecurityTrustResourceUrl method of the DomSanitizer:

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

Upvotes: 3

Related Questions