【发布时间】:2016-07-30 16:43:38
【问题描述】:
设置和运行一个组件并在不同位置以不同样式使用它的最佳做法是什么? (动态样式?)
【问题讨论】:
标签: angular
设置和运行一个组件并在不同位置以不同样式使用它的最佳做法是什么? (动态样式?)
【问题讨论】:
标签: angular
使用 :host-context() 在不同样式之间切换
通过应用不同的(预定义的类或属性)进行切换
:host-context(.class1) {
background-color: red;
}
:host-context(.class2) {
background-color: blue;
}
<my-comp class="class1></my-comp> <!-- should be red -->
<my-comp class="class2></my-comp> <!-- should be blue -->
使用全局样式
* /deep/ my-comp.class1 {
background-color: red;
}
// or to style something inside the component
* /deep/ my-comp.class1 /*deep*/ div {
border: solid 3px yellow;
}
* /deep/ my-comp.class2 {
background-color: blue;
}
使用主机绑定
@Component({
selector: 'my-comp',
host: {'[style.background-color]':'backgroundColor'}
})
class MyComponent {
@Input() backgroundColor:string;
}
<my-comp background-color="red"></my-comp>
<my-comp background-color="red"></my-comp>
另请参阅https://stackoverflow.com/a/36503655/217408 了解有趣的“黑客”。
【讨论】:
在我看来,最佳实践是通过组件的属性(属性)来控制样式。
【讨论】:
您可以在组件元数据中包含styleUrls/styles 选项,当该组件在视图上呈现时,您将使用这些选项。如果您将ViewEncasulation 用作Emulated/Native(将阴影DOM)会很好。
我建议阅读this great article
【讨论】: