您可以使用:host(...)
選擇與@HostBinding()
等組合:
@Component({
selector: 'my-comp',
styles: `
:host([type-default]) {
background-color: red;
}
:host([type-header]) {
background-color: blue;
}
:host([type-main]) {
background-color: green;
}
`
})
export class MyComponent {
@Input()
@HostBinding('component-type')
componentType:String="type-default"
}
,然後切換風格像
<header>
<my-comp componentType="type-header"></my-comp>
</header>
<main>
<my-comp componentType="type-main"></my-comp>
</main>
<my-comp></my-comp>
您也可以從外面你的問題中應用類等,然後使用:host(...)
選擇器like
:host(.customStyle1) {
那麼你不需要這部分
@Input()
@HostBinding('component-type')
componentType:String="type-default"
,但如果你想造型與該組件的其它配置設置,結合這種方式可能是有益的。
您可以在組件上添加customClass屬性並指定您在每個實例中需要的內容。 –
更新了OP。這是你的意思嗎?我試過了,但沒有奏效。 – user3715648
由於[查看封裝](https://angular.io/docs/ts/latest/guide/component-styles.html#!#view-encapsulation),您可能會遇到問題。可以嘗試在組件上將其指定爲None,或將自定義類添加到不綁定到特定組件的main.css文件中。 –