在 Angular 2 应用程序中跨组件共享样式

新手上路,请多包涵

我的 Angular 2 应用程序中有一些 CSS 规则,这些规则在各种组件中都很常见。显然我不想将它们复制并粘贴到每个组件的样式中。我目前有2个想法:

  1. 将通用 CSS 规则放在静态 CSS 文件中,并使用我的 index.html 的 head 部分中的链接将其包含在内。
  2. 将我常用的 CSS 规则放在一个或多个文件中,并将它们包含在每个组件的 @Component 装饰器中,例如 styleUrls: [ './myComponentStyle.css', '../common/common.css']

第一种方法对我来说看起来不那么棱角分明,但同时它肯定有效并且易于实现。

第二个需要对每个组件进行一些工作,但允许更多地控制一个组件正在使用哪些样式。它还允许我将常用样式组织成更小的样式表,并仅使用需要的样式表。

您赞成这些解决方案中的任何一个,还是有第三种更好的解决方案? :)

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

阅读 1k
1 个回答

对于未来的读者,我认为这个解决方案是最好的。

假设您有 2 个组件( 产品客户),并且有要共享的共同样式。

1.再创建一个组件

//customer-products-styles.component.ts
@Component({
  selector: "app-customer-products-styles",
  template: "",
  styleUrls: ["./customer-products-styles.component.scss"],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomerProductsStylesComponent {}

 //customer-products-styles.component.scss
app-products,
app-customers {
  p {
    color: coral;
  }
}

2.像这样使用它

<!-- Customers Component (app-customers) -->
<app-customer-products-styles></app-customer-products-styles>
<p>
  customers works!
</p>

 <!-- Products Component (app-products) -->
<app-customer-products-styles></app-customer-products-styles>
<p>
  products works!
</p>

好处

  • 它是延迟加载的,在下载模块块时加载,初始 main.js 减少
  • 添加组件选择器( app-customersapp-products )作为样式的父级使其成为组件范围
  • 没有重复的样式,并且只在浏览器中加载一次,无论组件首先请求它

一些附加点

  • encapsulation 设置为 none ,但将组件选择器添加为样式中的父级
  • 我还将默认 changeDetection 更改为 OnPush ,没有必要,但要安全

工作堆栈闪电战

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

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