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".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With