Html 角度最佳实践:为了可重用性,创建新的CSS类或新组件?
我有这个div和一组CSS属性(属性本身并不重要,它们只是示例),它们是我的应用程序的核心,我将在多个页面和其他组件中大量重用它们Html 角度最佳实践:为了可重用性,创建新的CSS类或新组件?,html,css,angular,angular8,Html,Css,Angular,Angular8,我有这个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> //这里会
<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,它们会根据所使用的上下文而变化
考虑到这是如此简单的html,并且没有数据/事件绑定会与此div
交互,这里最好的做法是什么(以及为什么):
- 新的CSS类
- 包含
内部的新角度组件 - 还有别的吗
<div class="myBaseStyle">
<ng-content></ng-content>
</div>
由于您希望在多个位置重用该div,因此创建组件是一种非常好的做法,因为如果您需要编辑该特定div中的某些内容,您只需要在一个位置而不是在每个位置更新它。如果将来您需要向该DIV添加更多html,您将不得不重新调整整个解决方案。从我所看到的情况来看,最好的解决方案是简单地创建一个CSS类,如下所示:
div.flex-container{
显示器:flex;
弯曲方向:立柱;
身高:100%;
}
原因:
- 不会引入额外的html嵌套,这会导致与flexbox之类的东西发生摩擦,因此不易维护
- 他们的模板由多个html元素组成(在问题的示例中只有一个)
- 它们利用自定义逻辑,无论是在类型脚本还是角度模板语法中,例如
ngIf
src文件夹下的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.
...
}
}
不太清楚你想做什么,但可能是两种做法的结合,你应该做一个css来包含你的风格,但我不确定你是否想把ng内容放在那个分区内。@DiegoBascans我做了一些编辑,希望现在更清楚了。你能详细说明为什么吗?例如,我可以不用制作新组件,只要在需要的地方使用myBaseStyle
类的div
s就可以了。
<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.
...
}
}
@extend .flex-container;
display: block;