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

时间:2017-03-16 02:56:10

标签: css angular angular-cli external

以下代码是为样式定义的。

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

我想将上述文件添加到< head>在'src / index.html'中由条件。

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

如您所知,我不能在'index.html'中使用'条件'代码。

请注意,我不会使用以下方法。

.fill-screen {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
}

.make-it-fit {
    max-width: 99%;
    max-height: 99%;
}


@font-face {
    font-family: 'Poppins', sans-serif;
    font-family: 'Josefin Slab', serif;
}

body {
    background-color: #f9f9f9;
}

fieldset {
    margin-top: 1em;
    margin-bottom: 1em;
    padding: .5em;
}
legend {
    color: blue;
    font-weight: bold;
    font-size: 85%;
    margin-bottom: .5em;
}
label {
    float: left;
    width: 90px;
}
input, select {
    margin-left: 1em;
    margin-right: 1em;
    margin-bottom: .5em;
}
input {
    width: 14em;	
}
input[type="radio"], input[type="checkbox"] {
    width: 1em;
    padding-left: 0;
    margin-right: 0.5em;
}

我期待着你的建议。

谢谢。

1 个答案:

答案 0 :(得分:13)

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

  1. 在index.html中:

    您将拥有如下的样式表链接:

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

    请注意,有&#34; id&#34;对于链接元素。

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

    从平台浏览器导入DOCUMENT

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

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

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

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