A guide on dynamically adding a CSS stylesheet to an Angular component during runtime

I have a requirement to dynamically inject a stylesheet into a component at runtime. The CSS url needs to change depending on user configuration settings and the selected theme.

Using styelUrls for static injection won't work in this case, as it is set during compile time.

Directly injecting the style link into the component also does not seem to be effective:

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

I've experimented with various approaches including interpolation and using @import() style, but none of them seem to work with a dynamically assigned value.

The necessary resources are included and everything works if I hardcode a specific style link. However, when attempting to set the value at runtime, an error occurs:

core.js:6228 ERROR Error: unsafe value used in a resource URL context (see )

While this makes sense, I am struggling to find a method to dynamically assign a stylesheet at runtime.

What would be the appropriate approach to achieve this?

Answer №1

To avoid the error, you can resolve it by deactivating Angular's sanitization using the bypassSecurityTrustResourceUrl function from the DomSanitizer:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for positioning the popup ul in relation to its parent li

How can the pop-up ul be positioned in the center of the parent li using CSS? * { margin: 0; padding: 0; } #track-nav { margin-left: 50px; margin-top: 50px; float: left; width: 100%; list-style: none; font-weight: bold; margin-bottom: ...

Error: NullInjector - The injector encountered an error when trying to inject the Component into the MatDialogRef in the AppModule

When utilizing a component via routing as well as injecting it as the "target" of a modal dialog, I encountered an issue: export class Component1 implements OnInit { constructor(private service: <someService>, public dialogRef: MatDialogRef<Compo ...

Unable to submit data to PHP script using Angular 2

I am currently attempting to send a post request to a PHP script that contains the necessary data I require. Within home.component.ts: import { Component, OnInit } from '@angular/core'; import { UserComment } from '../definition/us ...

What is the process for uploading this JSON data to Firestore and performing queries on it?

Can someone please guide me on how to push the following JSON data into firestore using Angular? var customer = { "name": "john", "address": "xxxxx", "order": { "bookList": [{ "quantity": "3", "price": ...

Is there a way to prevent the Drop event in Angular2?

In my Angular2 application, I have created a directive for an input field. To prevent paste or Ctrl+V within the host element of this directive, I used the following code which is functioning flawlessly: @HostListener('paste', ['$event&apos ...

Stopping all child events upon clicking (when navigating to a different tab) in RxJS

Currently, I am fetching all the designs (let's say 100) from the database and iterating through them. For each design, I am fetching the design image using a child component. <div *ngFor="let design of designs"> <div (click)="sho ...

Setting constraints for table size with min-width and max-height

I have a coding dilemma involving the min-width and max-height properties in my table. The issue arises when I try to set these properties on the td element – they are being ignored by the browser. If I nest a div with the properties inside a td, the con ...

Responsive design not functioning properly for Bootstrap columns on website

If my display currently looks like this with three equally distanced images at the top and two images at the bottom, how can I achieve that design? I attempted using Bootstrap by setting the top 3 images as <div className="col-md-4"> and t ...

Troubleshooting Problems with Cascading Style Sheets

Struggling with a layout issue on my website. I need to display an image with text at the beginning of the site-wrap div under the name background-image, with the text inside that div. Adding line-height to the text div adjusts its height, but I want to m ...

The width of Kendo Angular 2 grids pager and top header does not increase when scrolling

Our grids now have the horizontal scrolling feature enabled through CSS (kendo-grid {overflow: auto;}). However, we've noticed that the pager and top header of the grids do not expand their width when scrolling. Take a look at the screenshot below: ...

Circle a component around another on the vertical axis (z-index)

A plugin caught my eye some time back, but I'm having trouble locating it. This nifty tool operates by positioning an element behind another one, then smoothly sliding it to the right. After that, it changes the z-index so the element appears larger i ...

How to Ensure an Absolutely Positioned Element Occupies the Full Width of its Container

My main content area has a sidebar positioned absolutely to the right side due to various reasons. However, I am facing an issue where if the main content area is shorter, the sidebar extends beyond the content. Do you know of any CSS technique that can h ...

Any tips on animating my SVG when I hover my mouse over it with CSS or JavaScript?

Having trouble getting the gray outline to fill when hovering over it. The method I'm currently using isn't working on any browser. Any suggestions? You can find the HTML with the inline SVG file below: CSS is in a separate file, containing cla ...

"Changing the location of the suffix icon in an ant datepicker: step-by-step

Is there a way to relocate the calendar icon without using flex-flow:row-reverse? I'm open to exploring alternative methods. ...

Creating a dynamic form that efficiently captures user information and automatically redirects to the appropriate web page

Sorry for the unusual question, but it was the best way I could think of asking. I have come across websites with fill-in-the-blank lines where you can input your desired information and then get redirected to another page. For example: "What are you sea ...

Modify visibility or enable state of a text box according to a checkbox in PHP

Currently, I am utilizing PHP to exhibit a vertical list of numbered checkboxes, with one checkbox for each day in a specific month. Next to every checkbox, there is a text box where users can input optional notes for the selected day. To ensure that users ...

"Step-by-step guide on placing an order for the button

I am currently working with material-ui and encountering a roadblock. My goal is to design a homepage for a dashboard where the various services are listed. I am attempting to organize these 6 buttons into 2 rows and 3 columns, totaling 6 buttons in all. A ...

Issue with the integration of Angular and Java Jersey API arises when attempting to encode utf-8 whitespaces at the end, resulting in invalid JSON

I'm facing an issue with Angular while making an HTTP GET request. It throws a "Http failure during parsing" error because the JSON response contains whitespace characters at the end. I find it puzzling why the server is returning them. Is there a wa ...

Observable subscription not updating HTML with changes

My challenge is passing an object to the Object Model using a shared service to an already loaded component. Even though I receive data after subscribing, it does not reflect in the HTML view. <div *ngFor="let emp of emps" class="card&q ...

Using Javascript to save basic high scores to a server

My JS game involves updating a score variable. When the game reaches a gameOver state, I want to compare the score to one saved on the server. If the player got a higher score, I'd like to overwrite the previous high score with the new one. If it&apos ...