angular2:如何根据条件手动将css文件添加到index.html? [英] angular2: how to manually add css files by condition to index.html?

查看:85
本文介绍了angular2:如何根据条件手动将css文件添加到index.html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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">

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

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

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

How can I apply a css file for each device?

如您所知,我不能在"index.html"中使用有条件的"代码.

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

我期待您的建议.

谢谢.

推荐答案

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

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

  1. 在index.html中:

  1. In index.html:

您将拥有一个样式表链接,如下所示:

You will have a stylesheet link as follows:

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

请注意,链接元素有"id".

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

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

In your component you will have as follows:

从平台浏览器导入文档

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

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

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

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

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

这篇关于angular2:如何根据条件手动将css文件添加到index.html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆