如何在 Angular 2 中更改应用程序范围的 css?

San*_*ale 3 css stylesheet angular2-directives angular2-template angular

在我的应用程序中,我有不同的 CSS 文件,如 fire.css、lake.css,每个文件都为完整的应用程序提供了不同的外观。

目前,我只用 1 个文件 main.css 实现并将这个文件添加到
index.html

<link rel="stylesheet" href="resources/styles/main.css">  
<link rel="stylesheet" href="resources/styles/themes.css">
<link rel="stylesheet" href="resources/styles/common.css">
<link rel="stylesheet" href="resources/styles/plugins.css">
Run Code Online (Sandbox Code Playgroud)

现在我想在用户从下拉列表中选择时动态更改它。

我的想法:将所有 css 文件复制到 app 文件夹并在那里添加主题。
文件夹结构是

app
|-----app.component.ts
|-----app.routes.ts
|-----main.css
|-----lake.css
|-----登录
|- ----其他组件...

我在app.components.ts App 组件中添加了 css 到 styleUrls现在是

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({

    selector: 'workshop-app',    
    template: `
        <body>
           <router-outlet></router-outlet>
       </body>
    `,
    directives : [ ROUTER_DIRECTIVES ],
    styleUrls : ['app/lake.css']
})
export class AppComponent { }
Run Code Online (Sandbox Code Playgroud)

Lake.css 文件中的内容被添加到样式标签下,但不会在应用程序中进行更改。

Hie*_*ran 5

将此添加到 app.component.html

<head>
<link id="theme" rel='stylesheet' href='demo.css'>    
</head>  
Run Code Online (Sandbox Code Playgroud)

将此添加到 app.component.ts

import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';    
constructor (@Inject(DOCUMENT) private document) { }
ngOnInit() {
  this.document.getElementById('theme').setAttribute('href', 'demo2.css');
}
Run Code Online (Sandbox Code Playgroud)