What is the best practice to set up and run one component and use it with different styles in different locations? (dynamic styles?)
Asked
Active
Viewed 3,039 times
3 Answers
7
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".

Community
- 1
- 1

Günter Zöchbauer
- 623,577
- 216
- 2,003
- 1,567
-
1Yes, :host-context() is perfect for me. Thanks. – Javier RB Apr 09 '16 at 13:08
-
unpracticable when one need a whole stylesheet per theme, If you have thousands of classes and need like 10 themes... – Phil May 19 '17 at 09:20
-
I don't see how your comment and my answer are related. – Günter Zöchbauer May 19 '17 at 09:22
1
You could have styleUrls
/styles
options inside you Component metadata, that you would be use, when that component gets rendered on view. It would be good if you use ViewEncasulation
as Emulated
/Native
(will shadow DOM).
I'd recommend to read up on this great article

Pankaj Parkar
- 134,766
- 23
- 234
- 299
0
According to me the best practice would be controlling the styles through properties(attributes) of the component.

sreeramu
- 1,213
- 12
- 19