1

Todo :

  • css file based on subdomain loaded.
    For e.g: I have abc.css, xyz.css and these css should be loaded based on subdomains like if abc then abc.css must be loaded and so on.


Tried Cases :

  • Dynamically load css from angular-cli.json (Couldn't found a way to load dynamically)
  • Loading css on index.html (MiME type issue encountered)
  • Use style-loader on app init e.g require("style-loader!./style.css");


Used version : Angular 4.4.6 version.

Can anyone help me on this?
I am open to all suggestions, please suggest.

Thank You.

Abhishek Kumar
  • 2,501
  • 10
  • 25
NItesh Shrestha
  • 66
  • 3
  • 12

1 Answers1

0

Try this:

In the HTML template:
<link rel="stylesheet" [href]="getCssUrl()">

In the component.ts:

constructor (private sanitizer: DomSanitizer) {}

getCssUrl() {
    // Implement your code to return CSS url based on sub-domain
    const cssURL = xxx;
    return sanitizer.bypassSecurityTrustResourceUrl(cssUrl);
}
Charles Zhao
  • 158
  • 11
  • Encountered issue: unsafe value used in a resource URL context.. while returning '../custom.css' from the function. – NItesh Shrestha Aug 09 '18 at 05:59
  • Using DomSanitier will fix above issue but encountered another issue: Refused to apply style from 'http://localhost:4200/custom.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. – NItesh Shrestha Aug 09 '18 at 06:02
  • If `dom-sanitizer` is not helpful then you can refer to this issue on github : https://github.com/angular/angular-cli/issues/4685#issuecomment-279746337 Also, this if you can manipulate plain javascript in angular using renderer https://stackoverflow.com/questions/574944/how-to-load-up-css-files-using-javascript Hope, it helps. – Abhishek Kumar Aug 09 '18 at 06:14
  • Have you tried sanitizer.bypassSecurityTrustResourceUrl() method? I just edited my answer earlier. – Charles Zhao Aug 09 '18 at 06:41
  • If you still have MIME type issue, try to remove rel="stylesheet" from the html template. – Charles Zhao Aug 09 '18 at 06:47
  • I have found a blog post talking about the same solution as mine, and it does mention another solution using webpack. https://shekhargulati.com/2018/01/16/dynamically-loading-css-in-angular-5-application/ – Charles Zhao Aug 09 '18 at 06:53
  • I want to have file name based on sub-domain. removing rel-'styylesheet' remove MIME issue but not working as expected – NItesh Shrestha Aug 09 '18 at 09:47