【问题标题】:How to change app wide css in Angular 2?如何在 Angular 2 中更改应用程序范围的 css?
【发布时间】:2016-12-12 04:46:50
【问题描述】:

在我的应用程序中,我有不同的 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">

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

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

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

我在 app.components.ts 中的 styleUrls 中添加了 css 应用组件现在是

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 { }

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

【问题讨论】:

标签: css angular stylesheet angular2-template angular2-directives


【解决方案1】:

将此添加到 app.component.html

<head>
<link id="theme" rel='stylesheet' href='demo.css'>    
</head>  

将此添加到 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');
}

【讨论】:

  • 好答案!!!项目提交没有这个功能我有空试试。
  • 乐于助你,祝你好运
【解决方案2】:

在 Angular.json 文件中使用 fileReplacements:

"configurations": {
  "yourproject": { ... },
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/styles.css",
        "with": "src/new-styles.css"
      }
    ]
  }
}

您可以在这里更好地检查使用情况:https://angular.io/guide/build

【讨论】:

  • 他要求在用户输入某些操作时动态更改样式,而不是在构建时
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-01
  • 2022-01-22
  • 1970-01-01
  • 2012-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多