方式一:使用@Component的host属性
rush:js;">
@Component({
selector : 'myComponent',host : {
'[style.color]' : "'red'",'[style.background-color]' : 'backgroundColor'
}
})
class MyComponent {
backgroundColor: string;
constructor() {
this.backgroundColor = 'blue';
}
}
设置style:
- '[style.color]': "'red'":注意red值双引号里还有一个单引号。
- '[style.background-color]':'backgroundColor':这里是引用了组件里的变量backgroudColor。
这种方式的好处是可以在样式上使用组件的变量。
设置class:
rush:js;">
@Component({
selector : 'myComponent',host : {
'[class.myclass]' : 'showMyClass'
}
})
class MyComponent {
showMyClass = false;
constructor() {
}
toggleMyClass() {
this.showMyClass = !this.showMyClass;
}
}
方式二:在样式里使用:host选择器
rush:js;">
@Component({
selector : 'myComponent',styles : [`
:host {
color: red;
background-color: blue;
}
`]
})
class MyComponent {}