Angular 最佳实践:为了可重用性,制作新的 CSS class 或新组件?

Angular best practice: for reusability, make new CSS class or new component?

我有这个 div 和一组 CSS 属性(属性本身并不重要,它们只是示例)是我的应用程序的核心,我将重复使用遍及多个页面和其他组件。

<div style="display: flex; flex-direction: column; height: 100%">
//here there will be some inner html that will vary based on the context it's being used in
</div>

鉴于这是如此简单 html 并且 data/event 绑定不会与此交互 div,什么(以及为什么)是这里的最佳实践:

根据您的示例,您可能需要结合使用这两种做法。

<div class="myBaseStyle">
    <ng-content></ng-content>
</div>

你的 css 看起来像这样。

.myBaseStyle {
   display: flex;
   flex-direction: column;
   height: 100%
}

由于您想在多个地方重用 div,因此创建组件是一个很好的做法,因为如果您需要编辑特定 DIV 中的某些内容,您只需更新它在一个地方而不是在每个地方。如果将来您需要向 DIV 添加更多 html,您将不得不重构整个解决方案。

据我所知,我认为最好的解决方案是简单地制作一个 CSS class,如下所示:

div.flex-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

原因:

  • K.I.S.S.
  • 不引入额外的 html 嵌套,嵌套可能会与 flexbox 之类的东西产生摩擦,因此不易维护

在我看来,angular 组件只有在满足以下任一条件时才应创建:

  • 他们的模板由多个 html 元素组成(在问题的示例中只有一个)
  • 他们利用 TypeScript 或 angular 模板语法中的自定义逻辑,例如ngIf

在 angular 应用的 src folder 下的 style.css 中,制作一个全局样式如下:

<div class="flex-container">
  <ng-content></ng-content>
</div


.flex-container {
   display: flex;
   flex-direction: column;
   height: 100%;

   &.child-element { //like this you can add styles to chuld elements.
     ...
   }
}

通过这种方式,只需复制并粘贴您的 HTML,样式就会自动从 style.css 应用到根目录。

如果您想在特定组件的某处编辑样式,那么在任何一种情况下,您都可以将 style.css 文件中的样式 @extend 放入 x.compnent.css 您将获得x.compnent.css 中的先前样式,您可以按照自己的方式进行进一步更改。

@extend 样式示例:

@extend .flex-container;
  display: block;