Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an Angular 2 component style itself?

Tags:

angular

In Angular 2 you can include a stylesheet in a component's template. Because of Angular 2's View Encapsulation the styles only apply to the containing elements.

Is there a way to style the component's main tag without putting a surrounding <div class="component-wrapper"></div>?

Example plnkr: http://plnkr.co/edit/rANAsR1h9ERBIZV6wuJ8

It has an external css file adding a border and padding to the <app> tag, and the template attempts to set a background color.

like image 999
Ryan Avatar asked Jan 11 '16 22:01

Ryan


People also ask

How we can add style to the particular component in Angular?

There are several ways to add styles to a component: By setting styles or styleUrls metadata. Inline in the template HTML. With CSS imports.

How do I overwrite Angular materials in CSS?

Our solution to ViewEncapsulation was to override very specific css using highly specific css selectors in 1) global css or 2) creating separate style files for certain views / styles / elements, importing into every component required (e.g. styleUrls: [material-table-override.

How would you implement CSS logic in an Angular application?

Angular components can be styled via global CSS the same as any other element in your application. Simply drop a `<link>` element on your page (typically in index. html) and you're good to go! However, Angular additional gives developers more options for scoping your styles.


1 Answers

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 styles property and :host
@Component({     selector : 'my-component',     styles : [`         :host {             color: red;             background-color: blue;         }     `] }) class MyComponent {} 

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

Here's a plnkr with simple examples for both alternatives.

like image 59
Eric Martinez Avatar answered Oct 14 '22 11:10

Eric Martinez