相同的组件,不同的样式 [英] Same component, different styles

查看:41
本文介绍了相同的组件,不同的样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

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

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

 :host-context(.class1){背景颜色:红色;}:host-context(.class2){背景颜色:蓝色;} 

 < my-comp class ="class1></my-comp><!-应该是红色->< my-comp class ="class2></my-comp><!-应该是蓝色-> 

使用全局样式

 <代码> */deep/my-comp.class1 {背景颜色:红色;}//或在组件内部设置样式*/deep/my-comp.class1/* deep */div {边框:纯色3px黄色;}*/deep/my-comp.class2 {背景颜色:蓝色;} 

使用主机绑定

 <代码> @Component({选择器:"my-comp",主持人:{'[style.background-color]':'backgroundColor'}})类MyComponent {@Input()backgroundColor:string;} 

 <代码>< my-comp background-color ="red"></my-comp>< my-comp background-color ="red"></my-comp> 

另请参阅 https://stackoverflow.com/a/36503655/217408 ,其中有一个有趣的"hack"./p>

What is the best practice to set up and run one component and use it with different styles in different locations? (dynamic styles?)

解决方案

Switch between different styles using :host-context()

Switch by applying different (predefined classes or attributes)

: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 -->

Use global styles

* /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;
}

Use host-binding

@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>

See also https://stackoverflow.com/a/36503655/217408 for an interesting "hack".

这篇关于相同的组件,不同的样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆