3

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?

2
  • 1
    Did you try binding the result of DomSanitizer.bypassSecurityTrustResourceUrl(themeLink)? Commented Jul 20, 2020 at 21:48
  • No - didn't know that was a thing. Checking now. Thanks! Yes that works. Want to post that as the answer? this.themeLink = this.sanitizer.bypassSecurityTrustResourceUrl("themes/" + appModel.configuration.theme + "/theme.css"); Commented Jul 20, 2020 at 21:50

1 Answer 1

3

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.