Home > Software design >  How to dynamically load CSS with Angular
How to dynamically load CSS with Angular

Time:08-30

For the last couple of days I've been trying several answers, suggestions and tutorials for the problem, but unfortunately non of them did the trick.

The closest one was this:

https://juristr.com/blog/2019/08/dynamically-load-css-angular-cli/

But it uses "extractCss" which has been deprecated since the article has been published.

According to the article:

  1. "styles.js" file should disappear in the Inspector > Network > JS
  2. Clicking the button should add its css file in Inspector > Network > CSS

But neither of these two is happening at the moment.

app.component.ts

    const head = this.document.getElementsByTagName('head')[0];
    console.log(head);
    let themeLink = this.document.getElementById(
      'client-theme'
    ) as HTMLLinkElement;
    if (themeLink) {
      themeLink.href = styleName;
    } else {
      const style = this.document.createElement('link');
      style.id = 'client-theme';
      style.href = `${styleName}`;
      head.appendChild(style);
    }
  }

app.component.html

    <head>
    </head>
    <body>
        <button type="button" (click)="loadStyle('client-a-style.css')">STYLE 1</button> 
        <button type="button" (click)="loadStyle('client-b-style.css')">STYLE 2</button>     
    </body>
</html>

angular.json

"styles": [
              "src/styles.css",
              {
                "input": "src/client-a-style.css",
                "bundleName": "client-a",
                "inject": false
              },
              {
                "input": "src/client-b-style.css",
                "bundleName": "client-b",
                "inject": false
              }

These are the main parts of my code.

Hopefully I've explained the problem sufficiently. Thank you for helping!

CodePudding user response:

You can put your additionals .css in the folder assets (and remove from angular.json)

Then the only change is add the "assets" folder to the href

  loadStyle(styleName: string) {
    const head = this.document.getElementsByTagName('head')[0];

    let themeLink = this.document.getElementById(
      'client-theme'
    ) as HTMLLinkElement;
    if (themeLink) {
      themeLink.href = `assets/${styleName}`; //<--add assets
    } else {
      const style = this.document.createElement('link');
      style.id = 'client-theme';
      style.rel = 'stylesheet';
      style.type = 'text/css';
      style.href = `assets/${styleName}`; //<--add assets

      head.appendChild(style);
    }
  }

a stackblitz

CodePudding user response:

I think you are missing a property in the link tag, add this to the place you create the link element and it should work.

style.rel = 'stylesheet';

  • Related