angular2:如何按条件手动将 css 个文件添加到 index.html?

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

下面的代码是定义样式的。

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

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

我想按条件将上述文件添加到 'src/index.html' 中的 。

如何为每个设备应用一个 css 文件?

如你所知,我无法在 'index.html' 中使用 'Conditional' 代码。

注意下面的方法我不会用

// 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'
})

期待您的建议。

谢谢。

要动态加载或更改您的 CSS,您可以执行以下操作:

  1. 在index.html:

    您将有一个样式表 link 如下:

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

    请注意 link 元素有 "id"。

  2. 在您的组件中,您将具有以下内容:

    从平台浏览器导入文档

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

    然后,在您的操作或初始化中,您将相应地更改您的 css:

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

默认情况下,您将加载一个 CSS 文件。假设 desktop.css。在应用程序的根组件中,您可以查找设备或 cookie 或设置一些条件以从 desktop.css 更改为 mobile.css。就像你说的,你不会使用 angular-cli.json 来加载你的 CSS.