angular2: how to manually add css files by conditi

2020-02-26 11:43发布

问题:

The below code is that define for style.

<!-- for mobile -->
<link rel="stylesheet" href="/dist/css/mobile.css">

<!-- for desktop -->    
<link rel="stylesheet" href="/dist/css/desktop.css">

I want to add above files to <head> in 'src/index.html' by condition.

How can I apply a css file for each device?

As you know, I can't use 'Conditional' code in 'index.html'.

Note that I will not use the method below.

// in angular-cli.json
"apps": [
    {
        "root": "src",
        "index": "index.html",
        "styles": [
            "/dist/css/mobile.css",
            "/dist/css/desktop.css"
        ]
    }
]


// in component.ts
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrl: '/dist/css/mobile.css'
})

I look forward to your advice.

Thank you.

回答1:

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.