Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same component, different styles

Tags:

angular

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

like image 749
Javier RB Avatar asked Apr 09 '16 11:04

Javier RB


2 Answers

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

like image 110
Günter Zöchbauer Avatar answered Oct 30 '22 13:10

Günter Zöchbauer


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

like image 40
Pankaj Parkar Avatar answered Oct 30 '22 13:10

Pankaj Parkar