Can an Angular 2 component style itself?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)