Can Angular 2 style itself?

In Angular 2, you can include a stylesheet in a component template. Due to Angular 2 Encapsulation View, styles only apply to contained elements.

Is there a way to tweak the main component tag without putting the <div class="component-wrapper"></div> environment?

Plnkr example: http://plnkr.co/edit/rANAsR1h9ERBIZV6wuJ8

It has an external css file that adds a border and an addition to the <app> , and the template tries to set the background color.

+5
source share
1 answer

You have two options.

  • Use host property
 @Component({ selector : 'my-component', host : { '[style.color]' : "'red'", '[style.background-color]' : 'backgroundColor' } }) class MyComponent { backgroundColor: string; constructor() { this.backgroundColor = 'blue'; } } 
  • Use the styles property and :host
 @Component({ selector : 'my-component', styles : [` :host { color: red; background-color: blue; } `] }) class MyComponent {} 

Note there is an odd behavior when using :host and ViewEncapsulation.None .

Here plnkr with simple examples for both alternatives.

+17
source

Source: https://habr.com/ru/post/1240386/


All Articles