【问题标题】:how to replace angular theme CSS stylesheet for whole app?如何替换整个应用程序的角度主题 CSS 样式表?
【发布时间】:2020-09-17 20:18:18
【问题描述】:

首先我无法通过 index.html 导入 css,并且出现 MIME 类型错误: enter image description here 拒绝应用来自 'http://localhost:4200/css/pink-bluegrey.css' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。

如果我尝试通过 angular.json 导入它,那么我无法插入 ID 标签 id="themeAsset"。

我想添加 id 的原因是因为我想从 https://material.angular.io/guide/theming 执行此操作

函数 changeTheme(themeName) { document.getElementById('themeAsset').href = /path/to/my/${themeName}.css; } 所以我可以通过单击更改整个应用程序样式的样式,而不是向每个组件添加类

【问题讨论】:

  • 这个我不能通过 index.html 插入

标签: css angular theming


【解决方案1】:

工作 Stackblitz :- https://stackblitz.com/edit/angular-jrkmhn

我将我的 css 放在 assets 文件夹中,即 myStyles.css

CSS :-

.myDiv {
  background-color: black;
}

index.html

<link id="myLink">
<my-app>loading</my-app>

app.component.html

<div class="myDiv">Css Will Load</div>

<button style="margin-top: 2em" (click)="changeTheme('')">Change Theme</button>

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';


changeTheme(themeName) {
   var elem = document.getElementById('myLink');
   elem.setAttribute('href','./assets/myStyles.css');
   elem.setAttribute('rel','stylesheet');
   elem.setAttribute('type','text/css');
}
}

【讨论】:

  • 感谢您的快速回复,但如果您查看帖子,如果我尝试通过 index.html 添加 css,我在将 id="themeAsset" 插入 css 文件时遇到问题 我收到 MIME 错误
  • 尝试在路径末尾添加一个额外的 /。
  • 你的css不应该在assets文件夹中吗?因为资产是唯一以 Angular 提供服务的公共存储库?
  • 您好,在将其移至资产时,我已经设法通过解决方法做到了,感谢您的帮助!
  • 请投票作为答案,让其他人受益
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-15
  • 1970-01-01
  • 2021-05-05
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多