Javier RB
Javier RB

Reputation: 398

Same component, different styles

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

Upvotes: 5

Views: 3118

Answers (3)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657148

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

Upvotes: 7

sreeramu
sreeramu

Reputation: 1223

According to me the best practice would be controlling the styles through properties(attributes) of the component.

Upvotes: 0

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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

Upvotes: 1

Related Questions