5

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

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
Javier RB
  • 388
  • 1
  • 4
  • 10

3 Answers3

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