Angular2: How to Manually Add CSS Files by Condition to Index.Html

angular2: how to manually add css files by condition to index.html?

To dynamically load or change your CSS, you can do the following:

  1. In index.html:

    You will have a stylesheet link as follows:

    <link id="theme" href="assets/light.css" rel="stylesheet" >

    Note that there is "id" for the link element.

  2. In your component you will have as follows:

    Import the DOCUMENT from platform-browser

    import { DOCUMENT } from "@angular/platform-browser";

    then, in your action or on init you will change your css accordingly:

    this.document.getElementById('theme').setAttribute('href','assets/dark.css');

By default, you will load one CSS file.. lets say desktop.css. In your application's root component, you can look for the device or cookie or setup some conditions to change from desktop.css to mobile.css. Like you said, you will NOT use angular-cli.json to load your CSS.

Angular - including CSS file in index.html

Angular CLI have it's own way to initialize your global css/js.

They are located in .angular-cli.json configuration

Locate "styles": and add your css there

Example :

"styles": [
"../node_modules/angular2-busy/build/style/busy.css",
"styles.css"
],

Hope that helps.

Angular 2 - How to dynamically change an entire CSS stylesheet based on URL queryparams

After a lot of digging around, finally found the solution I was looking for.
And it was so straight forward, hope this helps others that might be needing to do the same thing..

Get the css path from query params and then Inject the Document into a TS file...
append the link to the head of the document.

I did this in a Router Guard using canActivate.
I got the query param from the routerstatesnpshot like so:

Inject the DOCUMENT( don't forget the import) in the constructor

http://server.com/xxx&broker=1&client=2&css=http://cssServer.com/my_dynamic_stylesheet.css

   import { DOCUMENT } from '@angular/common';

@Inject(DOCUMENT) private document: Document

this.setDynamicStyle(state.root.queryParamMap.get('css'));

setDynamicStyle(cssURL: string) {
const head = this.document.getElementsByTagName('head')[0];
const style = this.document.createElement('link');
style.id = 'css-styling';
style.rel = 'stylesheet';
style.href = `${cssURL}`;
head.appendChild(style);
}

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



Related Topics



Leave a reply



Submit