相同的组件,不同的风格

Jav*_* RB 2 angular

设置和运行一个组件并在不同位置使用不同样式的最佳实践是什么?(动态风格?)

Gün*_*uer 6

使用:host-context()在不同样式之间切换

通过应用不同的(预定义的类或属性)切换

:host-context(.class1) {
  background-color: red;
}

:host-context(.class2) {
  background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
<my-comp class="class1></my-comp> <!-- should be red -->
<my-comp class="class2></my-comp> <!-- should be blue -->
Run Code Online (Sandbox Code Playgroud)

使用全局样式

* /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;
}
Run Code Online (Sandbox Code Playgroud)

使用主机绑定

@Component({
  selector: 'my-comp',
  host: {'[style.background-color]':'backgroundColor'}
})
class MyComponent {
  @Input() backgroundColor:string;
}
Run Code Online (Sandbox Code Playgroud)
<my-comp background-color="red"></my-comp>
<my-comp background-color="red"></my-comp>
Run Code Online (Sandbox Code Playgroud)

另请参阅/sf/answers/2555255881/以获取有趣的"黑客".


Pan*_*kar 1

您可以在组件元数据中拥有styleUrls/styles选项,当该组件在视图上呈现时您将使用这些选项。ViewEncasulation如果你使用as Emulated/ Native(将遮蔽 DOM),那就太好了。

我建议阅读这篇很棒的文章