Angular 2 - 全局 CSS 文件

新手上路,请多包涵

是否可以将全局 CSS 文件添加到 Angular 2?目前,我有许多不同的组件具有相同的按钮样式 - 但每个组件都有自己的 CSS 文件和样式。这对于改变是令人沮丧的。

我在 Stack Overflow 上的某处读到添加:

 import { ViewEncapsulation } from '@angular/core'; //add this

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  encapsulation: ViewEncapsulation.None            //add this
})

所以我在根组件中添加了 ViewEncapsulation 行,然后将 CSS 样式添加到根应用程序 CSS (app.component.css) 并从单个组件 CSS 文件中删除了 CSS 样式,但它不起作用。

肯定有办法添加全局 CSS 文件吗?我是否需要向各个组件添加一些内容以使它们访问全局 CSS 文件?

原文由 dandev91 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 564
2 个回答

您可以简单地在主 html 文件中导入 css。

原文由 80sax 发布,翻译遵循 CC BY-SA 3.0 许可协议

只需在 src/styles.css 文件中写入全局样式。当您运行 --- 时,该文件将被添加到 styles.bundle.js ng build

如果您想添加更多样式文件,可以在 .angular-cli.json (或 angular.json 对于 Angular 6+)文件中添加。在该文件中,您将看到一个名为 styles 的数组,默认情况下有一个项目 styles.css (或 src/styles.css )。您甚至可以包含 .scss 文件。


使用 SCSS

If you want to use SCSS, simply change the extension of your src/styles.css file to .scss , then reflect the change in your .angular-cli.json (or angular.json 同样在 6+) 文件中,通过编辑 styles 数组中的条目。

让 Angular 默认使用 SCSS

创建组件时,您希望 Angular 创建 .scss 样式文件而不是 .css 。这是如何做:

角度 7

从 Angular 7 开始,当您使用 ng new appname 创建应用程序时,系统会提示您要使用哪种样式表格式,因此您只需选择 SCSS ( source )。似乎这里结束了手动配置 Angular 以使用 SCSS 的需要。

角度 6

在你的 angular.json 文件的末尾添加这个( source ):

 "schematics": {
  "@schematics/angular:component": {
    "styleext": "scss"
  }
}

Angular 4 及以下

.angular-cli.json 文件的末尾找到它,并将 --- 的值更改为 styleExt scss

 "defaults": {
  "styleExt": "css",
  "component": {}
}

原文由 Parziphal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题