Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically load CSS with Angular

Tags:

css

angular

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!

like image 879
librogil Avatar asked Jul 17 '26 00:07

librogil


1 Answers

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

like image 104
Eliseo Avatar answered Jul 18 '26 23:07

Eliseo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!